• 【LeetCode & 剑指offer刷题】树题5:110 Balanced Binary Tree


    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    110. Balanced Binary Tree

    Given a binary tree, determine if it is height-balanced.
    For this problem, a height-balanced binary tree is defined as:
    a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
    Example 1:
    Given the following tree [3,9,20,null,null,15,7]:
    Return true.
     
    Example 2:
    Given the following tree [1,2,2,3,3,null,null,4,4]:
    Return false.
     
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
     
    /*
    对于每一个节点,我们通过checkDepth方法递归获得左右子树的深度,
    如果子树是平衡的,则返回真实的深度,若不平衡,直接返回-1
    此方法时间复杂度O(N),空间复杂度O(H)
     
    对于用递归求解的题,可以画递归树来分析
    */
    class Solution
    {
    public:   
        bool isBalanced(TreeNode *root)
        {
            if (checkDepth(root) == -1) return false;
            else return true;
        }
       
        //类似问题:104. Maximum Depth of Binary Tree
        int checkDepth(TreeNode *root)
        {
            if (!root) return 0; //为空时,返回深度
           
            int left = checkDepth(root->left); //返回左子树的深度,如果不平衡,返回-1
            if (left == -1) return -1; //只要哪里有-1一路返回,直到递归结束
           
            int right = checkDepth(root->right); //返回右子树的深度
            if (right == -1) return -1;
           
            int diff = abs(left - right); //计算左右子树的深度差,如果不平衡,返回-1,平衡则返回实际深度
            if (diff > 1)
                return -1;
            else
                return 1 + max(left, right);
        }
    };
     
  • 相关阅读:
    redis中save和bgsave区别
    go语言标准库
    numpy 学习:数组改变形状、副本和view
    Python 开始:变量、操作符、print()和type()
    numpy 学习:数据类型和空值
    Python 数据类型:布尔类型和None
    numpy 学习:数组的拼接、堆叠和拆分
    numpy 学习:数组的查找
    Databricks 第12篇:Notebook 工作流
    numpy 学习:通用函数(包含数学函数)
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225786.html
Copyright © 2020-2023  润新知