【剑指offer】平衡二叉树

题目链接:平衡二叉树


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

 

题解:平衡二叉树的定义:左右子树高度之差不大于1。递归判断深度即可。

 

代码:

 1 class Solution {
 2 public:
 3     int depth(TreeNode* pRoot){
 4         if(pRoot == NULL )    return 0;
 5         int left = depth(pRoot->left);
 6         int right = depth(pRoot->right);
 7         if(left > right)    return left+1;
 8         else    return right+1;
 9     }
10     bool IsBalanced_Solution(TreeNode* pRoot) {
11         if(pRoot == NULL )    return true;
12         int left = depth(pRoot->left);
13         int right = depth(pRoot->right);
14         int sub = abs(left-right);
15         if(sub > 1)    return false;
16         return (IsBalanced_Solution(pRoot->left) && IsBalanced_Solution(pRoot->right));
17     }
18 };

 

posted @ 2020-03-04 22:32  甜酒果。  阅读(141)  评论(0编辑  收藏  举报