当前位置:网站首页>[leetcode] 93 balanced binary tree
[leetcode] 93 balanced binary tree
2020-11-10 01:15:00 【JaneRoad】
subject :
Their thinking :
Bottom up recursion
Similar to post order traversal , For the node currently traversed , First, recursively judge whether the left and right subtrees are balanced , Then judge whether the subtree with the current node as the root is balanced . If a subtree is balanced , Then return to its height ( The height must be a nonnegative integer ), Otherwise return to -1−1. If there is a subtree imbalance , Then the whole binary tree must be unbalanced .
Code :
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) >= 0;
}
public int height(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = height(root.left);
int rightHeight = height(root.right);
if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
return -1;
} else {
return Math.max(leftHeight, rightHeight) + 1;
}
}
}
版权声明
本文为[JaneRoad]所创,转载请带上原文链接,感谢
边栏推荐
猜你喜欢
Brief analysis of LinkedList source code
Simple use of JMeter
编码风格:Mvc模式下SSM环境,代码分层管理
jt-day10
What is the SRM system? SRM supplier management system functions
eleven point nine
Exception: invalid or unexpected token
Mongodb index management of distributed document storage database
For programmers, those unfamiliar and familiar computer hardware
《Python Cookbook 3rd》笔记(2.2):字符串开头或结尾匹配
随机推荐
将Map中对应的key和value赋值到对象中
CUDA_共享内存、访存机制、访问优化
大专学历的我工作六年了,还有机会进大厂吗?
Day85: Luffy: shopping cart switching price according to different validity period & shopping cart deletion operation & price settlement & foreplay of order page
proxy 的不完整polyfill
Validation failed for one or more entities. See ‘EntityValidationErrors’解决方法
lodash.js Source code flatten
极验无感验证破解
Make a home page
CUDA_全局内存及访问优化
Detach ()
pytorch训练GAN时的detach()
How much is the cost of CRM system?
Fear of reconstruction? I'm too late to tell you how to refactor. Now I'm here
day85:luffy:购物车根据有效期不同切换价格&购物车删除操作&价格结算&订单页面前戏
表单验证,为避免全局污染,少定义全局变量写法
js解决浏览器打印自动分页的问题
对于程序员,那些既陌生又熟悉的计算机硬件
CUDA_ Host memory
Experiment 2