Given a binary tree,imageine yourself standing on the right side of it,return the values of the nodes you can see orderd from top to bottom
1 <---
/ \
2 3 <---
\ \
5 4 <---
You should return
[1, 3, 4]
.
public static List<int> RightSideView(TreeNode root)
{
List<int> result = new List<int>();
Queue<TreeNode> queue = new Queue<TreeNode>();
Queue<TreeNode> next = new Queue<TreeNode>();
if (root == null)
{
return null;
}
else
{
queue.Enqueue(root);
}
while (queue.Count > 0)
{
List<int> level = new List<int>();
while (queue.Count > 0)
{
TreeNode node = queue.Dequeue();
level.Add(node.value);
if (node.Left != null)
{
next.Enqueue(node.Left);
}
if(node.Right!=null)
{
next.Enqueue(node.Right);
}
}
result.Add(level[level.Count - 1]);
var tmp = queue;
queue = next;
next = tmp;
}
return result;
}