LeetCode C++ 513. Find Bottom Left Tree Value【Tree/DFS/BFS】中等

111 篇文章 0 订阅
45 篇文章 0 订阅

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.

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


解法 BFS

找到最后一层的第一个节点:

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) { 
        queue<TreeNode*> q;
        q.push(root);
        TreeNode *ans = nullptr;
        while (!q.empty()) {
            int size = q.size(); 
            bool isfirst = false;
            for (int i = 0; i < size; ++i) {
                TreeNode *t = q.front(); q.pop();
                if (!isfirst) { ans = t; isfirst = true; }
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
        }
        return ans->val;
    }
};

执行效率如下:

执行用时:16 ms, 在所有 C++ 提交中击败了89.23% 的用户
内存消耗:21.8 MB, 在所有 C++ 提交中击败了23.13% 的用户

或者在进队的时候,先进队右子树,再进队左子树,这样最后出队的就是最后一行的最左边节点:

class Solution {
public:
    int findBottomLeftValue(TreeNode* root) { 
        queue<TreeNode*> q;
        q.push(root); 
        while (!q.empty()) {   
            root = q.front(); q.pop();  
            if (root->right) q.push(root->right);
            if (root->left) q.push(root->left); 
        }
        return root->val;
    }
};

执行结果如下:

执行用时:16 ms, 在所有 C++ 提交中击败了89.23% 的用户
内存消耗:21.7 MB, 在所有 C++ 提交中击败了28.29% 的用户
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

memcpy0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值