zoukankan      html  css  js  c++  java
  • 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.

    思路:

    一棵树是平衡二叉树,等价于两个子树都是平衡二叉树,并且两子树的深度差不超过1。

    代码:

     1     int max(int a, int b){
     2         if(a > b)
     3             return a;
     4         return b;
     5     }
     6     int getDepth(TreeNode *root){
     7         if(root == NULL)
     8             return 0;
     9         if(root->left == NULL && root->right == NULL)
    10             return 1;
    11         return 1+max(getDepth(root->left), getDepth(root->right));
    12     }
    13     bool isBalanced(TreeNode *root) {
    14         // Start typing your C/C++ solution below
    15         // DO NOT write int main() function
    16         if(root == NULL)
    17             return true;
    18         int d1 = getDepth(root->left), d2 = getDepth(root->right);
    19         if(d1 - d2 > 1 || d1 - d2 < -1)
    20             return false;
    21         return isBalanced(root->left)&&isBalanced(root->right);
    22     }

     

  • 相关阅读:
    第一次博客作业
    个人总结
    第三次个人作业——用例图设计
    第二次个人编程
    第一次个人编程
    第一次随笔
    个人总结
    第三次个人作业——用例图设计
    第二次结对作业
    第一次结对作业
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3409309.html
Copyright © 2011-2022 走看看