zoukankan      html  css  js  c++  java
  • 【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为树的高度。
  • 相关阅读:
    MyEclipse中代码提醒功能
    oracle12c创建用户等问题
    java中的构造块、静态块等说明
    jquery中的get和post、ajax有关返回值的问题描述
    最大半连通子图 BZOJ 1093
    最小生成树计数 BZOJ 1016
    水平可见直线 BZOJ 1007
    分金币 BZOJ 3293
    游走 BZOJ 3143
    糖果 BZOJ 2330
  • 原文地址:https://www.cnblogs.com/flix/p/12714254.html
Copyright © 2011-2022 走看看