2017 从上到下打印树新解法

老解法:

using namespace std;
struct Node {
    int value;
    Node* lchild;
    Node* rchild;
};
queue<Node*> Q;
void bfs(Node* pn) {
    if(pn == NULL) return;
    Q.push(pn);    
    while(!Q.empty()) {
        Node* t = Q.front();
        printf("%d ", t->value);
        if(t->lchild) {
            Q.push(t->lchild);
        }
        if(t->rchild) {
            Q.push(t->rchild);
        }
    }
}    
int main() {
    return 0;
}

或:

import java.util.*;
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {

        ArrayList<Integer> list =new ArrayList<Integer>();
        if(root==null) return list;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode t = queue.poll();
            list.add(t.val);
            if(t.left!=null) queue.add(t.left);
            if(t.right!=null) queue.add(t.right);
        }
        return list;
    }
}

有没有发现,都使用了队列或链表的结构, 其实没必要,只用数组就可以, 而且现代c/c++支持动态数组。

我用go写的。

package algorithm

import (
	"log"
	"errors"
)


func init(){
	bt := Btree{
		v:1,
		l: &Btree{
			v: 2,
			l: &Btree{
				v: 4,
				l: nil,
				r: &Btree{
					v: 5,
					l: nil,
					r: nil,
				},
			},
			r: nil,
		},
		r: &Btree{
			v: 3,
			l: nil,
			r: nil,
		},
	}
	printBtreeRow2(&bt)
	
}

func printBtreeRow2(btRoot *Btree) error {
	if nil == btRoot {
		return errors.New("invalid btRoot")
	}
	arr := []*Btree{btRoot}

	cntPTotal := 1
	for len(arr) >= cntPTotal {
		ele := arr[cntPTotal -1]
		if nil != ele.l {
			arr = append(arr, ele.l)
		}
		if nil != ele.r {
			arr = append(arr, ele.r)
		}
		cntPTotal += 1
		log.Println("row: ", ele.v)
	}
	return nil
}

 怎么样, 很清爽吧

原文地址:https://www.cnblogs.com/sunsky303/p/6844689.html