【LeetCode-树】找树左下角的值

题目描述

给定一个二叉树,在树的最后一行找到最左边的值。
示例:

输入:

    2
   / \
  1   3

输出:
1

输入:

        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

输出:
7

输入:
0
 \
  -1
输出:
-1

题目链接: https://leetcode-cn.com/problems/find-bottom-left-tree-value/

思路

注意,题目是让找最后一层最左边的节点值,不是找树最左边的节点值。使用递归来做,记录当前的深度和当前的最大深度,如果当前结点为叶子结点且当前深度大于当前的最大深度,则记录当前结点的值作为答案并更新当前的最大深度。代码如下:

/**
 * 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) {
        if(root==nullptr) return 0;

        int ans = root->val;   // 注意赋值,避免只有一个根结点出错的情况
        int maxDepth = -1;  // 目前最深的层
        int depth = 1;  // 目前的层
        search(root, depth, maxDepth, ans);
        return ans;
    }

    void search(TreeNode* root, int depth, int& maxDepth, int& ans){
        if(root==nullptr) return;
        if(root!=nullptr && root->left==nullptr && root->right==nullptr){   // 找到最后一层
            if(depth>maxDepth){ // 如果找到更深的层,更新答案
                ans = root->val;
                maxDepth = depth;
                return;
            }
        }

        search(root->left, depth+1, maxDepth, ans);
        search(root->right, depth+1, maxDepth, ans);
    }
};
  • 时间复杂度:O(n)
    n为树中的节点个数。
  • 空间复杂度:O(h)
    h为树的高度。

猜你喜欢

转载自www.cnblogs.com/flix/p/12714254.html