Leetcode题解:513. Find Bottom Left Tree Value

难度:Medium 类型:树

513. Find Bottom Left Tree Value

题目

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

概述

给定二叉树,找出其最底层的最左边元素
Input:

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

Output:
7

分析

其实所谓最底层节点,即为深度最深的节点,且该节点一定是叶子节点。所以只要用DFS遍历到最深的节点,这里可以采用前序遍历的方法,由于会先访问本节点的左子树,所以找到第一个深度最深的叶子节点即为最底层最左边节点。同样的,若问题求最底层最右边节点,只需要调换前序遍历左右子树遍历顺序先访问右子树即可。

当然也可以使用BFS的方法,从右子树节点开始加入队列,访问的队列中的最后一个节点就是所需要求得的最底层最左边节点。

参考代码给出的是前序遍历的方法。

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int curdepth = -1, maxdepth=-1;
    int ans;
    int findBottomLeftValue(TreeNode* root) {
        curdepth++;
        if(root->left==NULL && root->right==NULL){
            if(curdepth>maxdepth){
                ans = root->val;
                maxdepth = curdepth;
            }
        }
        if(root->left!=NULL)
            findBottomLeftValue(root->left);
        if(root->right!=NULL)
            findBottomLeftValue(root->right);
        curdepth--;
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值