[LeetCode513] Find the value in the lower left corner of the tree (dfs)

1. The topic

insert image description here
insert image description here

2. Ideas

  • dfs traverses a binary tree. In fact, you can use preorder traversal directly. Note that in order to find the earliest and deepest left node, you need to traverse the left subtree first, and then traverse the right subtree.
  • In order to satisfy the "deepest" condition, the current depthsum maxdepthvalue needs to be compared and updated maxdepth.
  • In fact, the question asks to find the leftmost node at the bottom. It does not specify that it must be the left child haha. If there is no left child, only the right child, then the right child is also the leftmost node.

3. Code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    
    
public:
    //这里的maxdepth不能初始化为0,因为是和实参0比较
    int left, maxdepth = -1;
    int findBottomLeftValue(TreeNode* root) {
    
    
        dfs(root, 0);
        return left;
    }
    void dfs(TreeNode* root, int depth){
    
    
        if(!root){
    
    
            return;
        }
        if(depth > maxdepth){
    
    
            left = root->val;
            ++maxdepth;
        }
        //先遍历左子树,再遍历右子树
        dfs(root->left, depth + 1);
        //注意这里当前节点的左孩子和右孩子的高度相同,并不会加2
        dfs(root->right, depth + 1);
    }
};

Guess you like

Origin blog.csdn.net/qq_35812205/article/details/124192112