LeetCode 513. Find Bottom Left Tree Value (Medium)

题目描述:

Given a binary tree, find the leftmost value in the last row of the tree.
Note: You may assume the tree (i.e., the given root node) is not NULL.

Example:
Input:

    2
   / \
  1   3

Output:
1

Input:

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

Output:
7
题目大意:给出一棵二叉树,求最深最左的叶子结点。

思路:遍历树,用一个“全局变量”记录树的当前遍历高度,如果一个叶子节点的深度比当前高度深,那这个叶子节点就是当前最深最左叶子结点。遍历完成就是答案。当然遍历方法不能是常规的,要保证最左的节点最后遍历,所以改写一下常规的前中后序遍历即可。
c++代码:

/**
 * 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 findBottomLeftValue(TreeNode* root) {
        curHeight = 0;
        int ans = root->val;
        myFind(root, 0, curHeight, ans);
        return ans;
    }
    void myFind(TreeNode* root, int height, int& curHeight, int& ans)
    {
        height++;
        if (root->right != NULL)
            myFind(root->right, height, curHeight, ans);
        if (root != NULL && height >= curHeight)
        {
            curHeight = height;
            ans = root->val;
        }
        if (root->left != NULL)
            myFind(root->left, height, curHeight, ans);  
    }
private:
    int curHeight;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值