LeetCode 513. 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.

/**
 * 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 maxdepth=0, answer;
    void finder(TreeNode *root, int depth){
        depth++;
        if(root->left)
            finder(root->left, depth);
        if(root->right)
            finder(root->right, depth);
        if(!root->left&&!root->right&&depth>maxdepth){
                answer=root->val;
                maxdepth=depth;
        }
    }
    int findBottomLeftValue(TreeNode* root) {
        finder(root, 0);
        return answer;
    }
};
posted @ 2018-12-05 22:16  A-Little-Nut  阅读(90)  评论(0编辑  收藏  举报