《劍指 offer》 學習22之從上往下打印二叉樹

題目描述

從上往下打印出二叉樹的每個節點,同層節點從左至右打印。
例如,以下二叉樹層次遍歷的結果爲:1,2,3,4,5,6,7
image.png

題目鏈接:牛客網

解題思路

使用隊列來進行層次遍歷。

不需要使用兩個隊列分別存儲當前層的節點和下一層的節點,因爲在開始遍歷一層的節點時,當前隊列中的節點數就是當前層的節點數,只要控制遍歷這麼多節點數,就能保證這次遍歷的都是當前層的節點。

import java.util.*;

public class Main {
    public static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;

        }

    }
    
	public static void main(String[] args) {
		TreeNode root = new TreeNode(1);
        root.right = new TreeNode(2);
        root.left = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        
        ArrayList list = printFromTopToBottom(root);
        printList(list);
	}
	
	public static ArrayList<Integer> printFromTopToBottom(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        ArrayList<Integer> list = new ArrayList<>();
        queue.add(root);
        
        while(!queue.isEmpty()) {
            int cnt = queue.size();
            while(cnt-- > 0) {
                TreeNode node = queue.poll();
                if (node == null) {
                    continue;
                } 
                list.add(node.val);
                queue.add(node.left);
                queue.add(node.right);
            }
        }
        
        return list;
    }
    
    public static void printList(ArrayList list) {
	    for (int i = 0;i < list.size();i++) {
	        System.out.print(list.get(i) + " ");
	    } 
	}
}

測試結果

image.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章