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 };
  • 相关阅读:
    FILE
    基础知识const/typedef/函数指针/回调函数
    strchr
    ftell
    rewind
    fread
    poj 2309BST解题报告
    hdoj 4004The Frog's Games解题报告
    哈理工oj 1353LCM与数对解题报告
    poj 2453An Easy Problem解题报告
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4683205.html
Copyright © 2011-2022 走看看