I am new to leetCode? How can we get the solution of the problems that we are solving??


  • -1
    V

    What is wrong with this solution?

    /**

    • Definition for binary tree
    • public class TreeNode {
    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */

    public class Solution {
    List<Integer> rightSide = new ArrayList<Integer>();
    public List<Integer> rightSideView(TreeNode root) {
    if(root == null){
    return rightSide;
    }
    while(root.right!=null){
    rightSide.add(root.val);
    root=root.right;

        }
        rightSide.add(root.val);
        return rightSide;
    }
    

    }


  • 0
    L

    your loop never end, and your solution is not right, you did not consider the left side, below is my solution:

    > int curLevel = 0; 
    > public List<Integer> rightSideView(TreeNode root) {
    >     List<Integer> list = new ArrayList<Integer>();
    >     dfs(root, 1, list);
    >     return list; }
    > 
    > private void dfs(TreeNode node, int level, List<Integer> list) {
    >     if (node == null) {
    >         return;
    >     }
    >     if (level > curLevel) {
    >         list.add(node.val);
    >         curLevel = level;
    >     }
    >     dfs(node.right, level + 1, list);
    >     dfs(node.left, level + 1, list); 
    > }
    

Log in to reply
 

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