zoukankan      html  css  js  c++  java
  • Balanced Binary Tree -- LeetCode

    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.

    思路:这题有两种方法。

    Top down approach

    设计一个depth函数,递归地返回一个子树的深度。

    一个BST平衡的条件为:为空;或者左右子树皆平衡,且左右子树的深度相差不超过1。

     1 class Solution {
     2 public:
     3     int depth(TreeNode *root)
     4     {
     5         if (!root) return 0;
     6         return max(depth(root->left), depth(root->right)) + 1;
     7     }
     8     bool isBalanced (TreeNode *root) {
     9         if (!root) return true;
    10         int left = depth(root->left);
    11         int right = depth(root->right);
    12         return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right); 
    13     }
    14 };

    复杂度分析:

    用master theory: depth函数为T(n) = 2T(n/2) + 1,为O(n);

    isBalanced函数为T(n) = 2T(n/2) + O(n),为O(nlogn)。

    如果这种方法想让时间复杂度降为O(n),则需要用map记录下每个子树的深度,以后就不需要再计算了。但空间复杂度为O(n)。

    Bottom up approach

    自底向上进行判断。使用一个help函数,若子树为平衡的,则返回该子树的深度,否则返回0。该方法每个节点只访问一遍,因此复杂度为O(n)。

     1 class Solution {
     2 public:
     3     int help(TreeNode *root)
     4     //balanced -- result >= 0
     5     //not balanced -- result = -1
     6     {
     7         if (!root) return 0;
     8         int left = help(root->left);
     9         if (left == -1) return -1;
    10         int right = help(root->right);
    11         if (right == -1) return -1;
    12         if (abs(left - right) > 1) return -1;
    13         return max(left, right) + 1;
    14     }
    15     bool isBalanced (TreeNode *root) {
    16         return help(root) != -1;
    17     }
    18 };
  • 相关阅读:
    补充之前对相机渲染的认识理解
    小公举---Content size Fitter 和 Aspect Radio Fitter
    UGUI事件响应体系
    基础组件RectTransform
    自适应神器------Canvas Scaler (画布定标器)
    UGUI初学习--------Canvas
    C#的集合类型及使用技巧
    C#基础之流程控制语句详解
    C#中的数据类型转换
    C#的基础数据类型
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5167920.html
Copyright © 2011-2022 走看看