39、剑指offer--平衡二叉树

题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
 
解题思路:平衡二叉树,对于每个根节点左右子树高度差小于等于1
 1 class Solution {
 2 public:
 3     int TreeDepth(TreeNode* pRoot)
 4     {
 5         if(pRoot == NULL)
 6             return 0;
 7         int nLeft = TreeDepth(pRoot->left);
 8         int nRight = TreeDepth(pRoot->right);
 9  
10         return (nLeft > nRight)?(nLeft+1):(nRight+1);
11     }
12     bool IsBalanced_Solution(TreeNode* pRoot) {
13         if(pRoot == NULL)
14         {
15             return true;
16         }
17         int nLeft = TreeDepth(pRoot->left);
18         int nRight = TreeDepth(pRoot->right);
19         int diff = nLeft-nRight;
20         if(diff < -1 || diff > 1)
21             return false;
22         return IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right);
23     }
24 };

 

posted @ 2017-06-14 18:18  qqky  阅读(124)  评论(0编辑  收藏  举报