标签:tree 平衡 ace null 左右子树 highlight turn 差值 javascrip
题目描述: 给定一个二叉树,判断它是否是高度平衡的二叉树。本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7],返回 true 。
//C
int maxDepth(struct TreeNode* root);
bool isBalanced(struct TreeNode* root){
if(root == NULL) return true;
return abs(maxDepth(root -> left) - maxDepth(root -> right)) <= 1 &&
isBalanced(root -> left) && isBalanced(root -> right);
}
int maxDepth(struct TreeNode* root){
if(root == NULL) return 0;
else if(root -> left == NULL && root -> right == NULL) return 1;
else {
int lheight = 0, rheight = 0;
lheight = maxDepth(root -> left);
rheight = maxDepth(root -> right);
return lheight > rheight ? lheight + 1 : rheight + 1;
}
}
//JS
let maxDepth = (node) => {
if(!node) return 0;
let leftDepth = maxDepth(node.left),
rightDepth = maxDepth(node.right);
return Math.max(leftDepth, rightDepth) + 1;
};
var isBalanced = function(root) {
if(!root) return true;
return Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1 &&
isBalanced(root.left) && isBalanced(root.right);
};
标签:tree 平衡 ace null 左右子树 highlight turn 差值 javascrip
原文地址:https://www.cnblogs.com/JesseyWang/p/13128919.html