题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
两点: 1.递归获取树深度
2.递归判断是不是平衡二叉树
第一点会了, 这题也就做出来了.
function IsBalanced_Solution(pRoot)
{
// write code here
if(!pRoot){
return true
}
return (Math.abs(getMaxDepth(pRoot.left)-getMaxDepth(pRoot.right))<=1
&& IsBalanced_Solution(pRoot.left)
&& IsBalanced_Solution(pRoot.right))
}
function getMaxDepth(root) {
if(!root) return 0
return Math.max(getMaxDepth(root.left)+1,getMaxDepth(root.right)+1)
}
module.exports = {
IsBalanced_Solution : IsBalanced_Solution
};
// /* function TreeNode(x) {
// this.val = x;
// this.left = null;
// this.right = null;
// } */
// function IsBalanced_Solution(pRoot)
// {
// // write code here
// function deep(root){
// if(root==null)return 0;
// let leftDeep=deep(root.left);
// let rightDeep=deep(root.right);
// return 1+Math.max(leftDeep,rightDeep);
// }
// function isPRoot(root){
// if(root==null)return true;
// let leftDeep=deep(root.left);
// let rightDeep=deep(root.right);
// let deepDiff=Math.abs(leftDeep-rightDeep);
// if(deepDiff<=1){
// return isPRoot(root.left)&&isPRoot(root.right);
// }else{
// return false;
// }
// }
// return isPRoot(pRoot);
// }
// module.exports = {
// IsBalanced_Solution : IsBalanced_Solution
// };