平衡二叉树

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。
#include<math.h>
class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        if(!pRoot)
                return true;
        int left=    GetLength(pRoot->left);
        int right = GetLength(pRoot->right);
        int diff = left-right;
        
        if(diff >1 || diff<-1){
            return false;
        }
        return IsBalanced_Solution(pRoot->left)&&IsBalanced_Solution(pRoot->right);
        
    }
    
    int GetLength(TreeNode *pRoot)
   {
        if(!pRoot)
            return 0;
        
        int leftDepth = GetLength(pRoot->left);
        int rightDepth = GetLength(pRoot->right);
        
        return (leftDepth > rightDepth)?(leftDepth+1):(rightDepth+1);
    }

};

 

posted on 2017-03-01 01:08  123_123  阅读(88)  评论(0)    收藏  举报