剑指 Offer 55 - I. 二叉树的深度
难度:简单
题目描述
解题思路
简简单单普普通通的递归
/*
* 剑指 Offer 55 - I. 二叉树的深度
* 2020//8/1
*/
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right)+1;
}
剑指 Offer 55 - II. 平衡二叉树
难度:简单
这道题可以直接用上面那道题的代码,分别比较左右子树的高度差是不是大于1。但是这样做效率不高,因为是从顶向下的,而且没有记忆化,每个节点都访问了多次。
/*
* 剑指 Offer 55 - II. 平衡二叉树
* 2020/8/1 难度:简单
*/
public boolean isBalanced(TreeNode root) {
if(root == null) {
return true;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
if(Math.abs(left-right) > 1) {
return false;
}
return isBalanced(root.left)&&isBalanced(root.right);
}
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right)+1;
}
效率更高的办法是用后续遍历的方式。这样在遍历到每个结点之前,我们已经遍历了它的左右子树。可以边遍历边判断每个节点是不是平衡的
对于一个节点,先遍历左子树,再遍历右子树,最后再来判断
每个子树的高度在自底向上递归的时候就已经计算出来了,避免重复的计算
//后序遍历,效率更高
public boolean isBalanced(TreeNode root) {
return isBalancedHelper(root) != -1;
}
public int isBalancedHelper(TreeNode root) {
if(root == null) { //如果遍历到空,返回高度0
return 0;
}
//先遍历左子树,再右子树
int left = isBalancedHelper(root.left);
if(left == -1) {
return -1;
}
int right = isBalancedHelper(root.right);
if(right == -1) {
return -1;
}
return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1;
}