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

Binary Tree Level Order Traversal

时间:2014-06-08 16:38:02      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:leetcode      层次遍历   java   

题目 

Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   /   9  20
    /     15   7

return its level order traversal as:

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

方法

树的层次遍历,使用Queue,并用一个计数器来标记下一层的元素个数。
PS:其实可以不用计数器,可以用队列元素的个数来统计。
    public List<List<Integer>> levelOrder(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);
        }
        return list;
    }



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

Binary Tree Level Order Traversal

标签:leetcode      层次遍历   java   

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

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