1.题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
2.算法描述
平衡二叉树是指每个结点的左右子树的高度之差不超过1的树。
利用二叉树的
前
序
遍
历
\red{前序遍历}
前序遍历,先判断根节点是否满足上述性质。然后判断左右子树是否满足上述性质。
3.代码描述
3.1.Java代码
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null)
return true;
int leftDepth = TreeDepth(root.left);
int rightDepth = TreeDepth(root.right);
if(leftDepth-rightDepth >= 2 || rightDepth-leftDepth >= 2)
return false;
return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
}
public int TreeDepth(TreeNode root) {
if(root == null)
return 0;
int leftDepth = TreeDepth(root.left);
int rightDepth = TreeDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
3.2.Python代码
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def IsBalanced_Solution(self, pRoot):
if not pRoot:
return True
leftDepth = self.TreeDepth(pRoot.left)
rightDepth = self.TreeDepth(pRoot.right)
if abs(leftDepth-rightDepth)>=2:
return False
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
def TreeDepth(self, pRoot):
if not pRoot:
return 0
leftDepth = self.TreeDepth(pRoot.left)
rightDepth = self.TreeDepth(pRoot.right)
return max(leftDepth, rightDepth) + 1