题目
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.
分析寻找一个二叉树的深度最左节点,可以通过计算二叉树深度的递归方法进行遍历,从左子树开始保证先找到最左节点,由于要找最深的最左节点,因此需要保存最大深度值,与当前深度作比较。
/**
* 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) {
int maxDepth=0;
int leftmost=root->val;
deepsearch(root,leftmost,maxDepth,0);
return leftmost;
}
void deepsearch(TreeNode* root,int& leftmost,int& maxDepth,int depth)
{
if(root==NULL)
return;
deepsearch(root->left,leftmost,maxDepth,depth+1);
deepsearch(root->right,leftmost,maxDepth,depth+1);
if(depth>maxDepth)
{
maxDepth=depth;
leftmost=root->val;
}
}
};