剑指offer-判断平衡二叉树

来源:互联网 发布:网络综艺为什么这么火 编辑:程序博客网 时间:2024/06/05 07:19

题目

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

题解

两个比较重要的部分:首先左右子树相差不大于1。然后所有子树都要为平衡二叉树。

代码

<?php/*class TreeNode{    var $val;    var $left = NULL;    var $right = NULL;    function __construct($val){        $this->val = $val;    }}*/function IsBalanced_Solution($pRoot){    // write code here    if($pRoot==null){return true;}    $left = TreeDepth($pRoot->left);    $right = TreeDepth($pRoot->right);    $dif = abs($left-$right);    if($dif>1){return false;}    return IsBalanced_Solution($pRoot->left)&&IsBalanced_Solution($pRoot->right);}function TreeDepth($root){    if(!$root || count($root)==0){return 0;}    $left = TreeDepth($root->left);    $right = TreeDepth($root->right);    return max($left,$right)+1;}