zoukankan      html  css  js  c++  java
  • Leetcode 110. Balanced Binary Tree

    110. Balanced Binary Tree

    • Total Accepted: 119517
    • Total Submissions:345415
    • Difficulty: Easy

    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且左右子树都是平衡树。

    方法二:设计了isDepth函数:如果root为根的树是平衡树,则返回树高;否则返回-1。

    代码:
    方法一:

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

    方法二:

     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     //如果root为根的树是平衡树,则返回树高;否则返回-1
    13     int isDepth(TreeNode* root){
    14         if(!root){
    15             return 0;
    16         }
    17         int left=isDepth(root->left);
    18         if(left==-1) return -1;
    19         int right=isDepth(root->right);
    20         if(right==-1) return -1;
    21         if(abs(left-right)<=1){
    22             return max(left,right)+1;
    23         }
    24         return -1;
    25     }
    26     bool isBalanced(TreeNode* root) {
    27         return isDepth(root)!=-1;
    28     }
    29 };
  • 相关阅读:
    详解CSS中:nth-child的用法
    网站哀悼变灰代码集合 兼容所有浏览器的CSS变暗代码
    简单CSS3实现炫酷读者墙
    CSS常用浮出层的写法
    五种方法让CSS实现垂直居中
    网页前端开发:微博CSS3适用细节初探
    CSS代码实例:用CSS代码写出的各种形状图形
    10个CSS简写及优化技巧
    25个站长必备的SEO优化工具
    40个让你的网站屌到爆的jQuery插件
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5655844.html
Copyright © 2011-2022 走看看