Can you explain the following lines? if(currDepth == result.size()){ result.add(curr.val); }


  • 0
    P

    Can you explain the following lines?

      if(currDepth == result.size()){
            result.add(curr.val);
        }

  • 0
    C

    This condition basically checks if we have already found the right-most visible element in a given depth.

    Suppose you have a tree like this :

      1            <--- depth= 0
     /   \
    2     3       <--- depth= 1
     \ 
      4            <--- depth= 2
     /
    5              <--- depth= 3
    

    [Note: your traversal order is : visit node, visit right subtree, visit left subtree ]

    1. When you call the function result.size()= currDepth= 0 --> result = { 1 }
    2. Visit right subtree: currDepth += 1, result.size()= currDepth = 1 --> result = { 1, 3 }
    3. recursive call winds back to node {1} currDepth= 0
    4. Visit left subtree : currDepth += 1, result.size() = 2 != currDepth= 1 --> Don't add 2 ! 3 is visible element from right hand side
    5. Same goes with {4} and { 5}

    Hope this clarifies the condition.


Log in to reply
 

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