binary-tree-level-order-traversal-ii

/**
* 給定一個二叉樹,返回該二叉樹由底層到頂層的層序遍歷,(從左向右,從葉子節點到根節點,一層一層的遍歷)
* 例如:
* 給定的二叉樹是{3,9,20,#,#,15,7},
* 3↵ / ↵ 9 20↵ / ↵ 15 7
* 該二叉樹由底層到頂層層序遍歷的結果是
* [↵ [15,7]↵ [9,20],↵ [3],↵]
*
*/

import java.lang.reflect.Array;
import java.util.ArrayList;

/**
 * 給定一個二叉樹,返回該二叉樹由底層到頂層的層序遍歷,(從左向右,從葉子節點到根節點,一層一層的遍歷)
 * 例如:
 * 給定的二叉樹是{3,9,20,#,#,15,7},
 *      3↵   / ↵  9  20↵    /  ↵   15   7
 * 該二叉樹由底層到頂層層序遍歷的結果是
 *      [↵  [15,7]↵  [9,20],↵  [3],↵]
 *
 */

public class Main50 {
    public static void main(String[] args) {
//        TreeNode root = null;
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(Main50.levelOrderBottom(root));

    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    public static ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        ArrayList<TreeNode> array = new ArrayList<>();
        if (root == null) {
            return list;
        }
        TreeNode head = root;
        array.add(head);
        while (!array.isEmpty()) {
            ArrayList<TreeNode> newArray = new ArrayList<>();
            ArrayList<Integer> subList = new ArrayList<>();
            for (TreeNode t : array) {
                if (t.left != null) {
                    newArray.add(t.left);
                }
                if (t.right != null) {
                    newArray.add(t.right);
                }
                subList.add(t.val);
            }
            array = newArray;
            list.add(0,subList);
        }
        return list;
    }

}
本站公眾號
   歡迎關注本站公眾號,獲取更多信息