leetcode 513. Find the value of the lower left corner of the tree

Problem: Given a binary tree, find the leftmost value in the last row of the tree.

Example 1:

enter:

2

/
1 3

Output:
1

Example 2:

enter:

    1
   / \
  2   3
 /   / \
4   5   6
   /
  7

Output:
7

Note: You can assume that the tree (ie the given root node) is not NULL.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/find-bottom-left-tree-value
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Code

class Solution {
    
    
    public int findBottomLeftValue(TreeNode root) {
    
    
        help(root,0);
        return list.get(list.size()-1);
        
    }
    List<Integer>list =new ArrayList<>();
    private void help(TreeNode root,int lev){
    
    
        if(root==null)
        return;
        if(list.size()-1<lev){
    
    
            list.add(root.val);
        }
        help(root.left,lev+1);
        help(root.right,lev+1);
        
    }
}

First traverse to add values ​​by layer and return the last value in the list.

Guess you like

Origin blog.csdn.net/qq_45789385/article/details/103451204