LeetCode -- Binary Tree Right Side View
題目描述:
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 RightSideView(TreeNode root) {
if(root == null){
return new List();
}
var result = new List();
RightView(new List(){root}, result);
return result;
}
public void RightView(IList nodes, IList 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();
foreach(var n in nodes){
var nl = Children(n);
if(nl.Any()){
children.AddRange(nl);
}
}
RightView(children, result);
}
private IList Children(TreeNode node){
if(node == null){
return new List();
}
var list = new List();
if(node.left != null){
list.Add(node.left);
}
if(node.right != null){
list.Add(node.right);
}
return list;
}
}