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

LeetCode -- Binary Tree Level Order Traversal

时间:2015-09-22 10:24:15      阅读:153      评论: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]
]




本题考查基本的BFS算法,把逐层遍历的节点添加到结果集中。


实现代码:




/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public IList<IList<int>> LevelOrder(TreeNode root) 
    {
        if(root == null){
		    return new List<IList<int>>();
    	}
    	
    	var starts = new List<TreeNode>();
    	if(root.left != null){
    		starts.Add(root.left);
    	}
    	if(root.right != null){
    		starts.Add(root.right);
    	}
    	
    	var result = new List<IList<int>>();
    	result.Add(new List<int>(){root.val});
    	Travel(starts, result);
    	return result;
    }


public void Travel(IList<TreeNode> parents, IList<IList<int>> result)
{
	// stop
	if(parents == null || parents.Count == 0){
		return ;
	}
	
	// add previous level nodes
	result.Add(parents.Select(x=>x.val).ToList());
	
	// get each parent childs and combine, do BFS
	var children = new List<TreeNode>();
	foreach(var n in parents){
		var nodes = Children(n);
		//add children
		children.AddRange(nodes);
	}
	
	Travel(children, result);
}


private IList<TreeNode> Children(TreeNode n)
{
	var nodes = new List<TreeNode>();
	if(n.left != null){
		nodes.Add(n.left);
	}
	if(n.right != null){
		nodes.Add(n.right);
	}
	
	return nodes;
}


}


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode -- Binary Tree Level Order Traversal

标签:

原文地址:http://blog.csdn.net/lan_liang/article/details/48650013

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