1. 程式人生 > >【劍指offer】面試題32(2):分行從上到下列印二叉樹

【劍指offer】面試題32(2):分行從上到下列印二叉樹

完整程式碼地址

題目

從上到下按層列印二叉樹,同一層結點從左至右輸出。每一層輸出一行。

思路

用佇列來儲存要列印的節點。
同時我們需要兩個變數:一個變量表示在當前層中還沒有列印的節點數;另一個變量表示下一層節點的數目。

程式碼

public class _32_02_PrintTreesInLines {

    public static class TreeNode {
        public int val = 0;
        public TreeNode left = null;
        public TreeNode right = null
; public TreeNode(int val) { this.val = val; } } public static ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { if(pRoot == null) return new ArrayList<>(); ArrayList<ArrayList<Integer>> result = new ArrayList<>(); Queue<TreeNode> queue = new
LinkedList<>(); queue.add(pRoot); ArrayList<Integer> lineResult = new ArrayList<>(); int numOfThisLine = 1; int numOfNextLine = 0; while(!queue.isEmpty()) { TreeNode node = queue.poll(); lineResult.add(node.val); --numOfThisLine; if
(node.left != null) { queue.add(node.left); ++numOfNextLine; } if(node.right != null) { queue.add(node.right); ++numOfNextLine; } if(numOfThisLine == 0) { result.add(lineResult); lineResult = new ArrayList<>(); numOfThisLine = numOfNextLine; numOfNextLine = 0; } } return result; } }

測試

public class _32_02_Test {

    public static void main(String[] args) {
        test1();
        test2();
        test3();
    }

    /**
     * 功能測試
     *     1
     *    / \
     *   2   3
     *  / \   \
     * 4   5   6
     */
    private static void test1() {
        TreeNode root = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        TreeNode node6 = new TreeNode(6);
        root.left = node2;
        root.right = node3;
        node2.left = node4;
        node2.right = node5;
        node3.right = node6;
        System.out.println(_32_02_PrintTreesInLines.Print(root));
    }

    /**
     * 邊界測試
     * 1.只有一個節點
     * 2.每個節點都只有左子節點
     * 3.每個節點都只有右子節點
     */
    private static void test2() {
        TreeNode root = new TreeNode(1);

        System.out.println(_32_02_PrintTreesInLines.Print(root));

        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        root.left = node2;
        node2.left = node3;

        System.out.println(_32_02_PrintTreesInLines.Print(root));

        root.left = null;
        node2.left = null;
        root.right = node2;
        node2.right = node3;
        System.out.println(_32_02_PrintTreesInLines.Print(root));
    }

    /**
     * 極端測試 
     * null
     */
    private static void test3() {
        System.out.println(_32_02_PrintTreesInLines.Print(null));
    }

}