劍指offer-22:從上往下列印二叉樹
阿新 • • 發佈:2018-12-11
題目描述
從上往下打印出二叉樹的每個節點,同層節點從左至右列印。
思路
二叉樹的層序遍歷,藉助一個佇列實現。
程式碼
public class Solution22 {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> arr=new ArrayList<>();
if(root==null)
return arr;
Queue< TreeNode> queue = new LinkedList<>();
TreeNode currentNode ;
queue.offer(root);
while (!queue.isEmpty()) {
currentNode = queue.poll();
if (currentNode.left != null)
queue.offer(currentNode.left);
if (currentNode.right != null)
queue.offer(currentNode.right);
arr.add(currentNode.val);
}
return arr;
}
public static void main(String[] args) {
int[] a={1,5,7,11,43,12,45,32,23,9,21};
TreeNode tree= BeanUtil.createCompleteBinaryTree(a);
BeanUtil. print(tree,tree.val,0);
BeanUtil.printArr(new Solution22().PrintFromTopToBottom(tree));
}
}