513. Find Bottom Left Tree Value**

本文介绍了解决LeetCode上513题FindBottomLeftTreeValue的方法,提供了两种有效的算法实现:一种是基于层序遍历的解决方案,通过记录每层最左边的元素找到最终答案;另一种是利用深度优先搜索(DFS),通过递归遍历左子树优先的方式,更新最深左侧节点的值。

513. Find Bottom Left Tree Value**

https://leetcode.com/problems/find-bottom-left-tree-value/

题目描述

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

Example 1:

Input:

    2
   / \
  1   3

Output:
1

Example 2:

Input:

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

Output:
7
  • Note: You may assume the tree (i.e., the given root node) is not NULL.

C++ 实现 1

层序遍历, 每一层记录最左边的第一个元素.

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) {
        queue<TreeNode*> q;
        int last = -1;
        q.push(root);
        while (!q.empty()) {
            auto size = q.size();
            for (int i = 0; i < size; ++ i) {
                auto r = q.front();
                q.pop();
                if (i == 0) last = r->val;
                if (r->left) q.push(r->left);
                if (r->right) q.push(r->right);
            }
        }
        return last;
    }
};

C++ 实现 2

采用 DFS 来做, 使用 res 记录最左侧的值, 同时用 max_depth 来记录当前访问的最大深度, 只有当 depth > max_depth 才对最大深度以及 res 进行更新. 由于先遍历左子树, 再遍历右子树, 所以:

if (depth > max_depth) {
    max_depth = depth;
    res = root->val;
}

这段代码会在遇到最深的最左侧的节点时执行, 该节点同一深度的其他节点, 因为深度均等于 max_depth, 所以该代码不会执行, 因此不会修改 res 中的值.

另外注意题目中说明了最少存在一个节点, 所以 res 初始化时设置为根节点的值.

class Solution {
private:
    int res, max_depth = 0;
    void dfs(TreeNode *root, int depth) {
        if (!root) return;
        if (depth > max_depth) {
            max_depth = depth;
            res = root->val;
        }
        dfs(root->left, depth + 1);
        dfs(root->right, depth + 1);
    }
public:
    int findBottomLeftValue(TreeNode* root) {
        res = root->val;
        dfs(root, 0);
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值