`
blue2048
  • 浏览: 183079 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

[leetcode]Binary Tree Level Order Traversal II - java

阅读更多

这个提跟Binary Tree Level Order Traversal 一样,只是结果集用栈

 

 

/**

 * Definition for binary tree

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

public class Solution {

   public List<List<Integer>> levelOrderBottom(TreeNode root) {

        LinkedList<List<Integer>> result = new LinkedList<List<Integer>>();

        if(root==null){

            return result;

        }

        List<Integer> rootValue = new ArrayList<Integer>();

        rootValue.add(root.val);

        result.push(rootValue);

        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();

        LinkedList<TreeNode> childrenQueue = new LinkedList<TreeNode>();

        queue.add(root);

        while (!queue.isEmpty()){

            TreeNode node = queue.remove();

            if(node.left != null){

                childrenQueue.add(node.left);

            }

            if(node.right!=null){

                childrenQueue.add(node.right);

            }

            if(queue.isEmpty() && !childrenQueue.isEmpty()){

                queue.addAll(childrenQueue);

                List<Integer> childValue = new ArrayList<Integer>();

                for(TreeNode child : childrenQueue){

                    childValue.add(child.val);

                }

                result.push(childValue);

                childrenQueue.clear();

            }

        }

        return result;

    }

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics