/** * 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 IListRightSideView(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; } }