标签:bottom top oid linked port rom etl treenode div
题目:
从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印
解答:
首先创建BinaryTreeNode
1 public class BinaryTreeNode { 2 int data; 3 BinaryTreeNode lchind; 4 BinaryTreeNode rchind; 5 6 public BinaryTreeNode(int data) { 7 this.data = data; 8 lchind = null; 9 rchind = null; 10 } 11 12 private int getData() { 13 return data; 14 } 15 16 private BinaryTreeNode getLchildNode() { 17 return lchind; 18 } 19 20 private void setLchildNode(BinaryTreeNode node) { 21 lchind = node; 22 } 23 24 private BinaryTreeNode getRchildNode() { 25 return rchind; 26 } 27 28 private void setRchildNode(BinaryTreeNode node) { 29 rchind = node; 30 } 31 }
接着:
1 import java.util.*; 2 3 public class Solution { 4 5 public static void main(String[] args) { 6 BinaryTreeNode node1=new BinaryTreeNode(8); 7 BinaryTreeNode node2=new BinaryTreeNode(6); 8 BinaryTreeNode node3=new BinaryTreeNode(10); 9 BinaryTreeNode node4=new BinaryTreeNode(5); 10 BinaryTreeNode node5=new BinaryTreeNode(7); 11 BinaryTreeNode node6=new BinaryTreeNode(9); 12 BinaryTreeNode node7=new BinaryTreeNode(11); 13 node1.setLchildNode(node2);node1.setRchildNode(node3); 14 node2.setLchildNode(node4);node2.setRchildNode(node5); 15 node3.setLchildNode(node6);node3.setRchildNode(node7); 16 17 printFromTopToBottom(node1); 18 } 19 20 private static void printFromTopToBottom(BinaryTreeNode root) { 21 if(root == null) { 22 return; 23 } 24 25 Queue<BinaryTreeNode> queue = new LinkedList<BinaryTreeNode>(); 26 27 queue.add(root); 28 29 while(!queue.isEmpty()) { 30 BinaryTreeNode node = queue.poll(); 31 System.out.println(node.getData()); 32 33 if(node.getLchildNode() != null) { 34 queue.add(node.getLchildNode()); 35 } 36 37 if(node.getRchildNode() != null) { 38 queue.add(node.getRchildNode()); 39 } 40 } 41 } 42 }
从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印
标签:bottom top oid linked port rom etl treenode div
原文地址:https://www.cnblogs.com/wylwyl/p/10366253.html