题目描述:
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;
};

375

被折叠的 条评论
为什么被折叠?



