javaScript题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function IsBalanced_Solution(pRoot)
{
// write code here
if(!pRoot) return true;
root_isBalanced = Math.abs(nodeHeight(pRoot.left)-nodeHeight(pRoot.right)) <= 1;
return root_isBalanced && IsBalanced_Solution(pRoot.left) && IsBalanced_Solution(pRoot.right);
}
function nodeHeight(node) {
if(!node) return 0;
return Math.max(nodeHeight(node.left), nodeHeight(node.right)) + 1;
}
module.exports = {
IsBalanced_Solution : IsBalanced_Solution
};
思路:
1、根据题意只需判断左右子树的高度差是否 <= 1
2、需要高度差,那必然需要先求出某一节点的高度。
2.1 求节点的高度,需要不断的向下搜索node的子节点,取左右两边最大的+1,直到叶子节点返回0。
3、root根节点是否平衡(整颗二叉树是否平衡)&& 左子树是否平衡 && 右子树是否平衡
查看14道真题和解析