zoukankan      html  css  js  c++  java
  • 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;
        }
    
    }
    

      

  • 相关阅读:
    UVA-679車的摆放(DFS)
    全排列问题(递归调用)
    STL栈的应用—UVA673
    nefu 84 五指山(扩展欧几里德)
    POJ 1061 青蛙的约会(扩展欧几里德)
    nefu 116 两仪剑法
    nefu 115 斐波那契的整除
    HDU 2099 整除的尾数
    Codeforces Round #339 (Div. 2) B. Gena's Code
    Codeforces Round #339 (Div. 2) A. Link/Cut Tree
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11356314.html
Copyright © 2011-2022 走看看