1、题目描述
2、题目分析
验证【平衡二叉树】,
一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
因此本题可以转换为:
1、求节点的深度 2、每个节点【左子树深度】和【右子树深度】差值为1
两种思路:
思路1:【自顶向下】就是从根节点逐步向下,发现每个节点都要验证左子树深度和右子树深度,再进行计算,这种方法显然复杂度较高,不推荐!代码如下,时间复杂度较高
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) return true;
return Math.abs(depth(root.left) - depth(root.right)) <= 1
&& isBalanced(root.left)
&& isBalanced(root.right);
}
private int depth(TreeNode root) {
if (root == null) return 0;
return Math.max(depth(root.left), depth(root.right)) + 1;
}
}
复杂度分析:
时间复杂度O(Nlog 2N): 最差情况下, isBalanced(root) 遍历树所有节点,占用 O(N);判断每个节点的最大高度 depth(root) 需要遍历 各子树的所有节点 ,子树的节点数的复杂度为 O(log_2 N) 。
空间复杂度 O(N): 最差情况下(树退化为链表时),系统递归需要使用 O(N)的栈空间。
思路2:【自下向上】就是先遍历到叶子结点,然后从下面到上面, 只有有一个节点不符合深度差值为1 的,就可以直接返回false了。
思路2:【自下向上】解题代码如下:
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int depth = depth(root);
if(depth == -1) return false;
return true;
}
private int depth(TreeNode root){
if(root == null) return 0;
int left = depth(root.left);
if(left == -1) return -1;
int right = depth(root.right);
if(right == -1) return -1;
if(Math.abs(left-right) > 1)
return -1;
return Math.max(left,right) +1;
}
}
复杂度分析:
时间复杂度 O(N): N 为树的节点数;最差情况下,需要递归遍历树的所有节点。
空间复杂度 O(N): 最差情况下(树退化为链表时),系统递归需要使用 O(N)的栈空间。