剑指offer 平衡二叉树

题目:

输入一棵二叉树,判断该二叉树是否是平衡二叉树。
 
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树

代码:

 1 class Solution {
 2 public:
 3     bool IsBalanced_Solution(TreeNode* pRoot) {
 4         if(pRoot == NULL) return 1;
 5         int count;
 6         count = DeepthOfTree(pRoot->left) - DeepthOfTree(pRoot->right);
 7         if(count > 1 || count < -1)
 8             return 0;
 9         return IsBalanced_Solution(pRoot->right) && IsBalanced_Solution(pRoot->left);
10     }
11     int DeepthOfTree(TreeNode* pRoot) {
12         if(pRoot == NULL) return 0;
13         return max(DeepthOfTree(pRoot->right)+1,DeepthOfTree(pRoot->left)+1);
14     }
15 };

我的笔记:

  通过计算每个结点的左右子树的深度,并计算差值,若差值为-1,0,1 则该子树为平衡二叉树,依次递归直至根节点,若差值均符合条件,则证明该树为平衡二叉树。

原文地址:https://www.cnblogs.com/john1015/p/13087981.html