判断二叉树是否为平衡二叉树
/* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /** * * @param root TreeNode类 * @return bool布尔型 */ function isBalanced( root ) { // write code here if(!root)return true var left_depth = getDeepth(root.left); var right_depth = getDeepth(root.right); if(Math.abs(left_depth-right_depth)<=1){ return isBalanced(root.left)&&isBalanced(root.right); }else{ return false; } } function getDeepth(node){ if(!node){ return 0; }else{ return 1 + Math.max(getDeepth(node.left),getDeepth(node.right)); } } module.exports = { isBalanced : isBalanced };
树算法 文章被收录于专栏
树相关算法