【leetcode】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.


 

题解:

一种方法是写一个递归求高度的函数,然后再写一个递归函数判断树是否是平衡的。

代码如下:

复制代码
 1 public class Solution {
 2     private int height(TreeNode root){
 3         if(root == null)
 4             return 0;
 5         int left = height(root.left);
 6         int right = height(root.right);
 7         
 8         return Math.max(left, right)+1;
 9     }
10     public boolean isBalanced(TreeNode root) {
11         if(root == null)
12             return true;
13         int left = height(root.left);
14         int right = height(root.right);
15         
16         if(Math.abs(left-right)>1)
17             return false;
18         return isBalanced(root.left) & isBalanced(root.right);
19     }
20 }
复制代码

这种方法耗时428ms。

第二种方法在递归求树的高度的过程中顺便判断树是否平衡,如果在某个节点处,该节点的左子树和右子树高度只差大于1,或者该树的左子树或者又子树不平衡,那么返回该树的高度为-1;否则返回该树的高度。

代码如下:

复制代码
 1 public class Solution {
 2     private int height(TreeNode root){
 3         if(root == null)
 4             return 0;
 5         int left = height(root.left);
 6         int right = height(root.right);
 7         
 8         if(left == -1 || right == -1 || Math.abs(left - right) > 1)
 9             return -1;
10         return Math.max(left, right)+1;
11     }
12     public boolean isBalanced(TreeNode root) {
13         return height(root) != -1;
14     }
15 }
复制代码

这种方法耗时464ms。

第二遍刷leetcode时候的java代码也放上来,耗时250ms。

复制代码
 1 public class Solution {
 2     public boolean isBalanced(TreeNode root) {
 3         height(root);
 4         return isBlanced;
 5     }
 6     boolean isBlanced = true;
 7     private int height(TreeNode root){
 8         if(root == null)
 9             return 0;
10         int leftheight = height(root.left);
11         int rightheight = height(root.right);
12         if(Math.abs(leftheight - rightheight) > 1){
13             isBlanced = false;
14         }
15         return Math.max(leftheight, rightheight)+1;
16     }
17 }
复制代码

 

posted @   SunshineAtNoon  阅读(164)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示