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

LeetCode Binary Tree Level Order Traversal

时间:2015-04-29 00:47:26      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

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]
]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ‘s Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where ‘#‘ signifies a path terminator where no node exists below.

Here‘s an example:

   1
  /  2   3
    /
   4
         5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".
题意:树的层次遍历。

思路:利用队列进行处理就行了,每次记录入队的有几个,就是下一层要访问的了

/**
 * 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>> levelOrder(TreeNode root) {
		List<List<Integer>> result = new ArrayList<List<Integer>>();
    	result.clear();
    	if (root == null) return result;
    	
    	LinkedList<TreeNode> q = new LinkedList<TreeNode>();
    	q.add(root);
    	int level = 0, count = 1;
    	while (!q.isEmpty()) {
    		List<Integer> tmp = new ArrayList<Integer>();
    		tmp.clear();
    		level = 0;
    		for (int i = 0; i < count; i++) {
    			root = q.pollFirst();
    			tmp.add(root.val);
    			if (root.left != null) {
    				q.add(root.left);
    				++level;
    			} 
    			if (root.right != null) {
    				q.add(root.right);
    				++level;
    			}
    		}
    		count = level;
    		result.add(tmp);
    	}
    	
    	return result;
    }
}



LeetCode Binary Tree Level Order Traversal

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45347741

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