Binary Tree Level Order Traversal II

来源:互联网 发布:美国种族歧视 知乎 编辑:程序博客网 时间:2024/06/05 04:09

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3   / \  9  20    /  \   15   7

return its bottom-up level order traversal as:

[  [15,7],  [9,20],  [3]]

public List<List<Integer>> levelOrderBottom(TreeNode root) {                List<List<Integer>> lists = new ArrayList<List<Integer>>();                if(root == null) return lists;                Queue<TreeNode> queue = new LinkedList<TreeNode>();        queue.add(root);                ArrayList<Integer> list = new ArrayList<Integer>();        int eachlayerSum = 1;        int parentSum = 0;                while(!queue.isEmpty()){                        TreeNode node = queue.peek();            list.add(node.val);            if(node.left != null){                queue.add(node.left);                parentSum ++;            }                        if(node.right != null){                queue.add(node.right);                parentSum ++;            }                        eachlayerSum --;            queue.remove();            if(eachlayerSum == 0){                lists.add(list);                list = new ArrayList<Integer>();                eachlayerSum = parentSum;                parentSum = 0;            }                    }                List<List<Integer>> listsnew = new ArrayList<List<Integer>>();        for(int i = lists.size()-1; i >= 0; i --){            listsnew.add(lists.get(i));        }                return listsnew;            }


0 0
原创粉丝点击