《剑指offer》Java实现--从上到下打印二叉树
2018-10-12 本文已影响10人
南湖Giser
题目描述
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
思路分析
额,好像没什么好分析的,这就是一个广度遍历,借用队列实现就可以了。
Java代码实现
import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
/**
* 从上倒下逐层遍历二叉树(广度遍历)
* @author Administrator
* @version 2018/10/12
*/
public class Exe33_PrintTreeFromTop2Down {
public static void main(String[] args) {
TreeNode node8=new TreeNode(8);
TreeNode node6=new TreeNode(6);
TreeNode node10=new TreeNode(10);
TreeNode node5=new TreeNode(5);
TreeNode node7=new TreeNode(7);
TreeNode node9=new TreeNode(9);
TreeNode node11=new TreeNode(11);
node8.leftTreeNode=node6;node8.rightTreeNode=node10;
node6.leftTreeNode=node5;node6.rightTreeNode=node7;
node10.leftTreeNode=node9;node10.rightTreeNode=node11;
print(node8);
}
//借用队列结构实现
public static void print(TreeNode root) {
if(root==null) return;
else {
Queue<TreeNode> queue=new LinkedBlockingDeque<TreeNode>();
queue.add(root);
TreeNode tempNode=null;
while(!queue.isEmpty()){
tempNode=queue.poll();
if(tempNode.leftTreeNode!=null)
queue.add(tempNode.leftTreeNode);
if(tempNode.rightTreeNode!=null)
queue.add(tempNode.rightTreeNode);
System.out.print(tempNode.treeVal+" ");
}
}
}
}
class TreeNode{
int treeVal;
TreeNode leftTreeNode;
TreeNode rightTreeNode;
public TreeNode(int value) {
this.treeVal=value;
}
@Override
public String toString() {
return "Node"+treeVal;
}
}