leetcode513

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.

这个题看起来就像是深度优先,感觉深度优先的题,很多都会让你写个辅助function,这个function要增加一些代表深度的变量level之类的,还可以视情况增加总深度或者头尾节点之类的,其中function中一般会用到递归去遍历。如果遇到求最小最大最深之类的,至少要给一个min/max变量,在适当的时候去和当前比较,该替换就替换,该保留就保留,嗯,大概就是酱紫。哦,递归还要注意停止递归的条件,对于深度优先,一般就是到了最深处停止咯。

/**
 * 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 max=0;
    int val=0;
    int findBottomLeftValue(TreeNode* root) {
        function(root,1);
        return val;
    }
    void function(TreeNode* root, int level){
        if(!root) return;
        if(level>max){
            max=level;
            val=root->val;
        }
        function(root->left,level+1);
        function(root->right,level+1);

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值