513. 找树左下角的值

给定一个二叉树,在树的最后一行找到最左边的值。

示例 1:

输入:

    2
   / \
  1   3

输出:
1

 

示例 2:

输入:

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

输出:
7

思路:维护一个最大深度max_depth如果深度更新,则对应的值也更新。这里注意先更新右边再更新左边,这样最后的值将会是最左边的值,左边的值会把右边的覆盖掉,如果深度相同的话

class Solution {
public:
    int max_depth=0;
    int res=0;
    void find(TreeNode* root,int depth)
    {   
        
        if(root==NULL) return ;
         if(depth>max_depth)max_depth=depth;
        if(!root->left&&!root->right&&depth>=max_depth){res=root->val;return;}//该节点为一个叶子节点而且大于等于最大深度那就更新
         find(root->right,depth+1);  
        find(root->left,depth+1);
     
    }
    int findBottomLeftValue(TreeNode* root) {
      find(root,0);
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/xuxuxuqian1/article/details/80726690