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

LeetCode -- Binary Tree Right Side View

时间:2015-09-19 19:45:27      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

题目描述:






Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.


For example:
Given the following binary tree,
   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
You should return [1, 3, 4].






思路:
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<int> RightSideView(TreeNode root) {
        if(root == null){
            return new List<int>();
        }
        
        var result = new List<int>();
        RightView(new List<TreeNode>(){root}, result);
        
        return result;
    }
    
    public void RightView(IList<TreeNode> nodes, IList<int> result)
    {
    	if(!nodes.Any()){
    		return;
    	}
        
        // add last node which is on the most right position	
    	result.Add(nodes.Last().val);
    	
    	// BFS
    	var children = new List<TreeNode>();
    	foreach(var n in nodes){
    		var nl = Children(n);
    		if(nl.Any()){
    			children.AddRange(nl);
    		}
    	}
    	
    	RightView(children, result);
    }




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


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

LeetCode -- Binary Tree Right Side View

标签:

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

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