Leetcode|二叉树的属性|513. 找树左下角的值

2021-09-18 15:56:25 浏览数 (1)

1.1 DFS

注意审题:是树最后一层最左边的值,不一定得是左叶子!因此只要从左至右深搜找到的第一个最深的节点即为该节点

代码语言:javascript复制
/**
 * 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 {
private:
    int left_val;
    int maxHigh = 0;
public:
    void dfs(TreeNode* root, int high) {
        if (!root) return;
        dfs(root->left, high   1);
        dfs(root->right, high   1);
        if (!root->left && !root->right && (high > maxHigh)) {
            maxHigh = high;
            left_val = root->val;
        }
    }
    int findBottomLeftValue(TreeNode* root) {
        dfs(root, 1);
        return left_val;
    }
};

1.2 回溯法

其实从左至右深搜发现最左节点不在最后一层,此时可以不用像DFS一样重新搜索,使用回溯法会略微高效点,待二刷的时候再更新啦~

2 BFS

代码语言:javascript复制
class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        if (!root) return 0;
        queue<TreeNode*> q;
        q.push(root);
        int left_val;
        while (!q.empty()) {
            int sz = q.size();
            for (int i=0;i < sz;i  ) {
                auto node = q.front(); q.pop();
                if (i==0)  // 记录每一层最左边的值
                    left_val = node->val;
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
        }
        return left_val;
    }
};
dfs

0 人点赞