力扣
答案:https://leetcode.cn/problems/ping-heng-er-cha-shu-lcof/solutions/832191/ping-heng-er-cha-shu-by-leetcode-solutio-6r1g/
Python
只遍历1次,自底而上的递归,本质是后序遍历
# 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:
res = self.judge(root)
return res >= 0
def judge(self, root) -> int:
if root == None:
return 0
left_depth = self.judge(root.left)
right_depth = self.judge(root.right)
if left_depth == -1 or right_depth == -1 or abs(left_depth - right_depth) > 1:
return -1
else:
return 1 + max(left_depth, right_depth)
Java
法1:遍历两次,思路一般
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
if (Math.abs(depth(root.left) - depth(root.right)) <= 1) {
return isBalanced(root.left) && isBalanced(root.right);
} else {
return false;
}
}
public int depth(TreeNode node) {
if (node == null) {
return 0;
}
return 1 + Math.max(depth(node.left), depth(node.right));
}
}
法2:只遍历1次
class Solution {
public boolean isBalanced(TreeNode root) {
return depth(root) >= 0;
}
public int depth(TreeNode node) {
if (node == null) {
return 0;
}
int left = depth(node.left);
int right = depth(node.right);
if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
return -1;
}
return 1 + Math.max(left, right);
}
}
20180906整理
##Solution1:
书上的思路,利用后序遍历,每个结点只遍历一次~
class Solution {
public:
bool IsBalanced_Solution(TreeNode* pRoot) {
int depth = 0;
return IsBalanced(pRoot, depth);
}
bool IsBalanced(TreeNode *pRoot, int &depth) {
if (pRoot == NULL) {
depth = 0;
return true;
}
int left, right;
if (IsBalanced(pRoot->left, left) &&
IsBalanced(pRoot->right, right)) {
int diff = left - right;
if (abs(diff) <= 1) {
depth = 1 + max(left, right);
return true;
}
}
return false;
}
};