题目来源于leetcode,解法和思路仅代表个人观点。传送门。
难度:简单
用时:00:10:00 (一开始有小漏洞)
题目
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
思路
本地两种解法,自顶向下和自底向上。
一开始只想到了自顶向下的方式。
分析之后,就会发现递归的条件:
一棵树是平衡二叉树,那么该节点,左子树和右子树也是平衡二叉树
自顶向下递归,因此对于同一个节点,获取深度函数会被重复调用,导致时间复杂度较高。如果使用自底向上的做法,则对于每个节点,获取深度函数只会被调用一次。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
自顶向下
class Solution {
/*
一棵树是平衡二叉树,那么该节点,左子树和右子树也是平衡二叉树
*/
public boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}
int left = getDeepth(root.left);
int right = getDeepth(root.right);
if(isBalanced(root.left) && isBalanced(root.right)){
if(Math.abs(left - right) <= 1){
return true;
}
}
return false;
}
public int getDeepth(TreeNode root){
if(root == null){
return 0;
}
return Math.max(getDeepth(root.left),getDeepth(root.right)) + 1 ;
}
}
自底向上
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;
}
}
}
算法复杂度
以下分析来自leetcode官方题解
自顶向下
时间复杂度: O(n2),其中 n 是二叉树中的节点个数。
空间复杂度: O(n),其中 n 是二叉树中的节点个数。空间复杂度主要取决于递归调用的层数,递归调用的层数不会超过 n。

自底向上
时间复杂度: O(n),其中 n 是二叉树中的节点个数。使用自底向上的递归,每个节点的计算高度和判断是否平衡都只需要处理一次,最坏情况下需要遍历二叉树中的所有节点,因此时间复杂度是 O(n)。
空间复杂度: O(n),其中 n 是二叉树中的节点个数。空间复杂度主要取决于递归调用的层数,递归调用的层数不会超过 n。

本文探讨了平衡二叉树的判断方法,提供了自顶向下和自底向上的两种递归解法。自顶向下方法虽然直观,但时间复杂度较高;自底向上方法则优化了计算过程,实现了更高效的O(n)时间复杂度。

152

被折叠的 条评论
为什么被折叠?



