LeetCode OJ-513.Find Bottom Left Tree Value

2 篇文章 0 订阅

LeetCode OJ-513.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.

Subscribe to see which companies asked this question.

题目理解

​ 题目要求二叉树的最底下一层最左边的节点,注意,这里的最左边的节点可能是一个节点的左子节点,也可能是一个节点的右子节点。另外,这只是普通的二叉树,并未说明是搜索二叉树,并不具备特殊性质。这里采用广度优先搜索是较好的处理方式,逐层搜索,使用队列queue辅助。

Code

typedef TreeNode tree_t; 

class Solution {
public:
    int findBottomLeftValue(TreeNode* t) {
        int res = 0;
        tree_t *tmp;
        queue<tree_t *> q;

        size_t sz = 0;
        q.push(t);
        while (!q.empty()) {
            sz = q.size();
            res = q.front()->val;  // 记录每层的最左节点的值
            while (sz--) {  // 将该层的其余节点的子节点加入队列,则可舍弃,因为只需关注最左
                tmp = q.front();
                q.pop();
                if (tmp->left != 0) {
                    q.push(tmp->left);
                }
                if (tmp->right != 0) {
                    q.push(tmp->right);
                }
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值