Why my java solution doesn't work? It works on Ideone.com


  • 0
    P
    public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> list=new ArrayList<Integer>();
        if(root!=null)
         {
         	list.add(root.val);
         	if(root.right!=null) 
         	    list.addAll(rightSideView(root.right));
         	    
         }
         
         return list;
    }
    

    }


  • 3
    C

    Possibly the problems are different. In this code you don't traverse the left side of tree at any point. What if the left side of the tree is deeper than the right side ?
    You will see those nodes when you look at from the RHS right ?


  • 0
    M

    Thank you!!! Your explanation is much clearer than the problem itself! This is a poorly worded problem, and the example makes matters worse.


  • 0
    P

    my java solution using DFS

    public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> list=new ArrayList<Integer>();
        Stack<TreeNode> stack=new Stack<TreeNode>();
        Stack<Integer>  deepth=new Stack<Integer>();
        
        if(root!=null) 
            { 
              stack.push(root);
              deepth.push(1);
            }
         int globaldeepth=0;
        while(!stack.empty())
         {
            TreeNode node=stack.pop(); 
             int deep=deepth.pop();
            if(globaldeepth<deep) 
            {
                list.add(node.val);
                globaldeepth=deep;
            }
         	if(node.left!=null)
         	   { stack.push(node.left);
         	     deepth.push(deep+1);
         	   }
         	if(node.right!=null)
         	  {  
         	      stack.push(node.right);
         	    deepth.push(deep+1);
         	  }
      }
         
         return list;
    }
    

    }


Log in to reply
 

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