[leetcode-107]Binary Tree Level Order Traversal II(java)

来源:互联网 发布:流程优化的目的和意义 编辑:程序博客网 时间:2024/04/27 01:54

原文链接

代码如下:368ms

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<List<Integer>> levelOrderBottom(TreeNode root) {        Stack<List<Integer>> stack = new Stack<>();        Queue<TreeNode> queue = new LinkedList();        List<List<Integer>> res  = new LinkedList<>();        queue.offer(root);        int count = 1;        while(!queue.isEmpty()){            int tmpCount = 0;            List<Integer> tmpList = new LinkedList();            for(int i = 0;i<count;i++){                TreeNode tmpNode = queue.poll();                if(tmpNode!=null){                    tmpList.add(tmpNode.val);                    queue.offer(tmpNode.left);                    queue.offer(tmpNode.right);                    tmpCount+=2;                }            }            count = tmpCount;            if(!tmpList.isEmpty())                stack.push(tmpList);        }        while(!stack.isEmpty()){            res.add(stack.pop());        }        return res;    }}
0 0