首页 > 其他 > 详细

面试题55 - II. 平衡二叉树

时间:2020-05-09 21:18:09      阅读:52      评论: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     int maxDepth(TreeNode *root)
13     {
14         if (NULL == root)
15         {
16             return 0;
17         }
18 
19         int maxdepth = std::max(maxDepth(root->left), maxDepth(root->right)) + 1;
20 
21         return maxdepth;
22     }
23     bool isBalanced(TreeNode* root) 
24     {
25         if (NULL == root)
26         {
27             return true;
28         }
29 
30         int leftdepth = maxDepth(root->left);
31         int rightdepth = maxDepth(root->right);
32 
33         if (std::abs(leftdepth - rightdepth) > 1)
34         {
35             return false;
36         }
37         else
38         {
39             return isBalanced(root->left) && isBalanced(root->right);
40         }
41     }
42 };

 

面试题55 - II. 平衡二叉树

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

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