Solution to Binary Tree right side view


  • 0
    S
    /**
     * 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) 
        {
            int maxLevelSeen = -1;
            List<int> list = new List<int>();        
            RightSideViewUtil(root, 0, ref maxLevelSeen, ref list);
            return list;
        }
        
        public void RightSideViewUtil(TreeNode root, int level, ref int maxLevelSeen, ref List<int> list)
        {
            if (root == null)
                return;
            
            if (level > maxLevelSeen)
            {
                maxLevelSeen = level;
                list.Add(root.val);
            }
            
            RightSideViewUtil(root.right, level + 1, ref maxLevelSeen, ref list);
            RightSideViewUtil(root.left, level + 1, ref maxLevelSeen, ref list);
        }    
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.