首页 > 其他 > 详细

【树】面试题 04.04. 检查平衡性

时间:2020-05-03 17:34:25      阅读:60      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

 

 

解答:

同题目"【树】高度平衡二叉树的判定"。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12    // 求深度
13     int depthTree(TreeNode *root)
14     {
15         int depth = 0;
16         if (root)
17         {
18             int leftdepth = depthTree(root->left);
19             int rightdepth = depthTree(root->right);
20 
21             depth = leftdepth > rightdepth ? (leftdepth + 1) : (rightdepth + 1);
22         }
23         return depth;
24     }
25 
26     bool isBalanced(TreeNode* root) 
27     {
28         if (NULL == root)
29         {
30             return true;
31         }
32 
33         int leftdepth = depthTree(root->left);
34         int rightdepth = depthTree(root->right);
35 
36         if (abs(leftdepth - rightdepth) > 1)
37         {
38             return false;
39         }
40         else
41         {
42             return isBalanced(root->left) && isBalanced(root->right);
43         }
44     }
45 };

 

【树】面试题 04.04. 检查平衡性

原文:https://www.cnblogs.com/ocpc/p/12822275.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!