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

    判断一棵二叉树是否为平衡二叉树

    C++(9ms):

     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 == NULL)
    14             return true ;
    15         return Depth(root) != -1 ;
    16     }
    17     
    18     int Depth(TreeNode* root) {
    19         if (root == NULL)
    20             return 0 ;
    21         int left = Depth(root->left) ;
    22         if (left == -1)
    23             return -1 ;
    24         int right = Depth(root->right) ;
    25         if (right == -1)
    26             return -1 ;
    27         if (abs(left - right) > 1)
    28             return -1 ;
    29         return max(left,right) + 1 ;
    30     }
    31 };
  • 相关阅读:
    Js 30 BOM
    js面向对象
    js模态窗口
    js默认行为(也称默认事件)
    框架的控件隐藏
    20150706 js之定时器
    sublime快捷方式和node.js
    js回调函数2
    Hibernate 多对一
    Hibernate入门之配置文件
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/8056242.html
Copyright © 2011-2022 走看看