【樹】高度平衡二叉樹的判定


題目:

 

 

解答:

平衡二叉樹要求左子樹和右子樹的高度相差為1,且左右子樹都是平衡二叉樹,顯然要計算二叉樹的高度的函數。

 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 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM