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.

    Analyse: Recursively judge

                 1. height difference of subtrees of the current root larger than 1

          2. whether the current root has balanced subtrees.

    Runtime: 20ms.

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     bool isBalanced(TreeNode* root) {
    13         if(!root) return true;
    14         if(!root->left && !root->right) return true;
    15         
    16         if(abs(depth(root->left) - depth(root->right)) > 1) return false;
    17         return isBalanced(root->left) && isBalanced(root->right);
    18     }
    19     int depth(TreeNode* root){
    20         if(!root) return 0;
    21         return max(depth(root->left), depth(root->right)) + 1;
    22     }
    23 };
  • 相关阅读:
    框架
    css样式表。作用是美化HTML网页.
    表单的制作
    表格的制作
    常用标签的制作
    标签的制作
    poj2104(K-th Number)
    Codeforces Round #359 (Div. 2) D. Kay and Snowflake
    Codeforces Round #359 (Div. 2) C. Robbers' watch
    HDU3308(LCIS) 线段树好题
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4683205.html
Copyright © 2011-2022 走看看