美文网首页
107. Binary Tree Level Order Tra

107. Binary Tree Level Order Tra

作者: namelessEcho | 来源:发表于2017-10-03 13:18 被阅读0次

    因为要求bottom-up 可以考虑使用一个stack。

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> result = new ArrayList<>();
            if(root==null)return result;
            Stack<List<Integer>> stack = new Stack<>();
            ArrayDeque<TreeNode> queue = new ArrayDeque<>();
            queue.add(root);
            while(!queue.isEmpty())
            {
                int size = queue.size();
                List<Integer>  list = new ArrayList<>();
                for(int i = 0 ;i<size;i++)
                {
                    TreeNode node = queue.poll();
                    list.add(node.val);
                    if(node.left!=null)
                        queue.add(node.left);
                    if(node.right!=null)
                        queue.add(node.right);
                }
                stack.push(list);
            }
            while(!stack.isEmpty())
            {
                result.add(stack.pop());
            }
            return result ;
        }
    }
    

    相关文章

      网友评论

          本文标题:107. Binary Tree Level Order Tra

          本文链接:https://www.haomeiwen.com/subject/yizxyxtx.html