点击查看剑指Offer全解【Java & Golang】实现
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
思路
补充概念:
平衡二叉树(Balanced Binary Tree)具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
第一种做法是递归地获取到树的左右子树深度,若深度之差大于1,则说明其不是平衡二叉树。这种做法需要先递归地获取到左右子树的深度。
第二种做法是第一种做法的改进版本,即在每一次获取左右子树深度时都判断一次差值,若差值大于1,则直接返回深度为-1,表示该局部子树已经不是平衡二叉树,那么接下来就无需在计算深度了;若差值小于等于1,那么继续返回最大深度,由上层调用者继续判断。
Java第一种实现
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
// 边界条件
if (root == null) {
return true;
}
// 获取左右子树的深度,判断差值是否小于等于1,成立则说明为平衡二叉树,
return Math.abs(getDepth(root.left) - getDepth(root.right)) <= 1;
}
private int getDepth(TreeNode root) {
// 递归终止条件
if (root == null) {
return 0;
}
return Math.max(getDepth(root.left), getDepth(root.right)) + 1;
}
}
Java第二种实现
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
// 边界条件
if (root == null) {
return true;
}
return getDepth(root) != -1;
}
private int getDepth(TreeNode root) {
// 递归终止条件
if (root == null) {
return 0;
}
// 获取左右子树的深度
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
// 若返回的深度有一者为-1,则说明其子树不是平衡二叉树,继续返回-1
if (leftDepth == -1 || rightDepth == -1) {
return -1;
}
// 若两子树的深度不为-1,则继续判断其深度之差是否小于等于 ;
// 若等于,则继续向上返回最大深度,若不等于,返回-1
return Math.abs(leftDepth - rightDepth) <= 1 ?
Math.max(leftDepth, rightDepth) + 1 : -1;
}
}
Golang第二种实现
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isBalanced(root *TreeNode) bool {
if root == nil {
return true
}
return getDepth(root) != -1
}
func getDepth(root *TreeNode) int {
if root == nil {
return 0
}
leftDepth := getDepth(root.Left)
rightDepth := getDepth(root.Right)
if leftDepth == -1 || rightDepth == -1 {
return -1
}
if leftDepth - rightDepth > 1 || rightDepth - leftDepth > 1 {
return -1
}
return max(leftDepth, rightDepth) + 1
}
func max(a, b int) int {
if a > b {
return a
} else {
return b
}
}
407



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



