码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Level Order Traversal II

时间:2014-06-08 09:23:34      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:leetcode      层次遍历   java   

题目

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,#,#,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>> list = new ArrayList<List<Integer>>();
    	
    	if (root == null) {
    		return list;
    	}
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int count = 1;
        while (!queue.isEmpty()) {
        	int len = count;
        	count = 0;
        	List<Integer> subList = new ArrayList<Integer>();
        	for(int i = 0; i < len; i++) {
        		TreeNode curNode = queue.poll();
        		subList.add(curNode.val);
        		if (curNode.left != null) {
        			queue.offer(curNode.left);
        			count++;
        		}
        		if (curNode.right != null) {
        			queue.offer(curNode.right);
        			count++;
        		}
        	}
        	list.add(subList);
        }
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        for (int i = list.size(); i > 0; i--) {
            result.add(list.get(i - 1));
        }
        return result;
    }


Binary Tree Level Order Traversal II,布布扣,bubuko.com

Binary Tree Level Order Traversal II

标签:leetcode      层次遍历   java   

原文地址:http://blog.csdn.net/u010378705/article/details/28621053

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!