博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Balanced Binary Tree
阅读量:4625 次
发布时间:2019-06-09

本文共 1108 字,大约阅读时间需要 3 分钟。

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 };

 

转载于:https://www.cnblogs.com/amazingzoe/p/4683205.html

你可能感兴趣的文章
jQuery:1.5.5.2,京东导航(当前默认设置)
查看>>
ASP.NET中 DetailsView(详细视图)的使用前台绑定
查看>>
我又情不自禁了——立方网的又一次加速度
查看>>
如何屏蔽国内IP访问我们的网站的一些方法!
查看>>
起与伏
查看>>
2.网络编程-udp
查看>>
Handlebars.js 模板引擎
查看>>
MySQL体系结构
查看>>
Nginx-日志切割
查看>>
219. Insert Node in Sorted Linked List【Naive】
查看>>
CentOS下安装mysql及配置使用
查看>>
Sublime Text3配置Vue 语法
查看>>
验证控件:RegularExpressionValidator
查看>>
hdu1166 线段树单点修改与区间查询
查看>>
asp.net -mvc框架复习(7)-基于MVC搭建用户登录项目框架
查看>>
CSS background-clip 属性
查看>>
python中函数作用域
查看>>
C#版清晰易懂TCP通信原理解析(附demo)
查看>>
系统自带的粒子系统
查看>>
Laravel 框架的主要版本
查看>>