题目
题目:从上往下打印二叉树的每个节点,同一层的节点按照从左到右的顺序打印
思路
如果没有想到使用容器,这个题很难往下做。
如果使用容器的话:先打印根节点的值,然后把它的两个子节点放入容器中,先取出左节点,打印其值,然后把它的两个节点放入容器,再打印右节点,再把它的两个节点放入容器,依次类推。。
java代码
package com.co;
import java.util.LinkedList;
class Node{
int value;
Node leftTree;
Node rightTree;
public Node(int value){
this.value = value;
}
}
public class PrintTwoForkTree {
public static void main(String[] args) {
Node root = new Node(8);
root.leftTree = new Node(2);
root.leftTree.leftTree = new Node(5);
root.leftTree.rightTree = new Node(9);
root.rightTree = new Node(3);
root.rightTree.rightTree = new Node(4);
LinkedList<Node> list = new LinkedList<Node>();
print(root,list);
}
public static void print(Node root,LinkedList<Node> list){
if(root == null){
return;
}
System.out.print(root.value + " ");
if(root.leftTree != null || root.rightTree != null){
list.offer(root.leftTree);
list.offer(root.rightTree);
}
if(list == null){
return;
}
Node nodeOne = list.poll();
while(nodeOne == null){
nodeOne = list.poll();
}
print(nodeOne,list);
}
}