小黑代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
self.status = True
# 求深度
def get_depth(node):
if not node:
return 0
left_h = get_depth(node.left)
right_h = get_depth(node.right)
if abs(left_h - right_h) > 1:
self.status = False
return max(left_h,right_h) + 1
get_depth(root)
return self.status
自顶向下递归(python)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
# 求高度
def get_depth(node):
if not node:
return 0
return max(get_depth(node.left),get_depth(node.right)) + 1
if not root:
return True
return abs(get_depth(root.left)-get_depth(root.right)) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
自顶向下递归(java)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}
return Math.abs(get_depth(root.left) - get_depth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
}
public int get_depth(TreeNode node){
if(node == null){
return 0;
}
int left_h = get_depth(node.left);
int right_h = get_depth(node.right);
return Math.max(left_h,right_h) + 1;
}
}
自底向上递归(python)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
# 求高度
def get_depth(node):
if not node:
return 0
left_height = get_depth(node.left)
if left_height == -1:
return -1
right_height = get_depth(node.right)
if right_height == -1 or abs(right_height - left_height) > 1:
return -1
return max(left_height,right_height) + 1
return get_depth(root) != -1
自底向上递归(java)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
return get_depth(root) != -1;
}
public int get_depth(TreeNode node){
if(node == null){
return 0;
}
int left_h = get_depth(node.left);
if(left_h == -1){
return -1;
}
int right_h = get_depth(node.right);
if(right_h == -1 || Math.abs(right_h - left_h) > 1){
return -1;
}
return Math.max(right_h,left_h) + 1;
}
}