DataStructure_Algorithm_HandBook_PreForLeetCode

513. Find Bottom Left Tree Value

Given the root of a binary tree, return the leftmost value in the last row of the tree.

Example 1:

img

Input: root = [2,1,3]
Output: 1

Example 2:

img

Input: root = [1,2,3,4,null,5,6,null,null,7]
Output: 7

Constraints:

solution

这道题目的思路和上一题的思路基本一致,但是由于是找左下角的值,可以加个深度来判断。 也不需要sum 叠加每次的 val了,当深度变大的时候就更新就可以了/ 我这边就不写 bfs 的方法了,只写dfs

层序遍历的思路也是一样,每一层都更新一下i = 0 的时候的值就可以了

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        dfs(root,1);
        return sum;
    }
    int sum = -1;
    int max_depth = 0; 
    void dfs(TreeNode node,int depth){
        if(node == null) return ; 
        if(node.left == null && node.right == null && depth > max_depth){
           max_depth = depth;
           sum = node.val;
        }
        dfs(node.left,depth+1);
        dfs(node.right,depth+1);
    }
}