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; } };
相关文章推荐
- Medium:Find Bottom Left Tree Value
- LeetCode - 513 - Find Bottom Left Tree Value
- leetcode 513 Find Bottom Left Tree Value C++
- LeetCode 513 Find Bottom Left Tree Value(二叉树层序遍历)
- LeetCode- Find Bottom Left Tree Value
- Leetcode 513 Find Bottom Left Tree Value
- leetcode 513 Find Bottom Left Tree Value
- [LeetCode]Find Bottom Left Tree Value 寻找二叉树最左树叶的值
- 【Leetcode513 Find Bottom left Tree Value】树的遍历
- 【LeetCode】Find Bottom Left Tree Value 解题报告
- leetcode513 FindBottomLeftTreeValue Java
- [LeetCode]Find Bottom Left Tree Value
- LeetCode——Find Bottom Left Tree Value
- LeetCode:Find Bottom Left Tree Value
- [LeetCode] Find Bottom Left Tree Value 寻找最左下树结点的值
- lintcode/leetcode由易至难第18题:Find Bottom Left Tree Value
- 513[Medium]:Find Bottom Left Tree Value
- [LeetCode]513 Find Bottom Left Tree Value(BFS)
- LeetCode之Find Bottom Left Tree Value
- LeetCode Find Bottom Left Tree Value