平衡二叉树

平衡二叉树

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

  • 平衡二叉树是左右深度差不超过1的二叉树,所以在遍历深度的同时需要判断是否深度差超过1。
1
2
3
4
5
6
7
8
9
10
11
12
13
function IsBalanced_Solution(pRoot)
{
// write code here
return TreeDepth(pRoot)!==-1;
}
function TreeDepth(pRoot){
if(pRoot==null)return 0;
const leftdep=TreeDepth(pRoot.left);
if(leftdep==-1)return -1;
const rightdep=TreeDepth(pRoot.right);
if(rightdep==-1)return -1;
return Math.abs(leftdep-rightdep)>1? -1 : Math.max(leftdep,rightdep)+1
}