您的位置:首页 > 产品设计 > UI/UE

LeetCode Find Bottom Left Tree Value [Medium]

2017-09-24 17:09 351 查看

原题地址

题目内容



题目分析

题目的意思为:找到整棵树最后一行最左边的那个数。采用先序遍历的方法,用maxdepth来记录当前最深的的层数,res来记录当前最左的数值。depth来记录当前遍历所在的层数。这里要注意一点的就是判断条件是depth>maxdepth而不是depth>=maxdepth。因为先序遍历是先遍历左子树,所以res肯定是记录leftmost,而如果depth>=maxdepth的话,结果就有可能会变成记录到leftmost的兄弟了,比如在example1中输出的结果就会为3而不是1.

代码实现

/**
* 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:
void findleftval(struct TreeNode* root, int depth, int& res, int& maxdepth){
if(root == NULL){
return;
}
findleftval(root->left,depth+1,res,maxdepth);
findleftval(root->right, depth+1,res,maxdepth);

if(depth > maxdepth){
maxdepth = depth;
res = root->val;
}
}

int findBottomLeftValue(TreeNode* root) {
int maxdepth = 0;
int res = root->val;
findleftval(root,0,res,maxdepth);
return res;
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: