微软面试题: LeetCode 110. 平衡二叉树 出现次数:2

题目描述:

 

 

 代码:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 class Solution {
 4 public:
 5     bool isBalanced(TreeNode* root)
 6     {
 7        int h = 0;
 8        return isBalancedHelper(root,h);
 9     }
10 
11     bool isBalancedHelper(TreeNode* root,int &height)
12     {
13         if(root == nullptr)
14         {
15             height = 0;
16             return true;
17         }
18         int left_h = 0;
19         int right_h = 0;
20         bool left_res = isBalancedHelper(root->left,left_h);
21         bool right_res = isBalancedHelper(root->right,right_h);
22         height = max(left_h,right_h) + 1;//二叉树 root 的高度
23         return left_res && right_res && abs(left_h - right_h) <= 1;
24     }
25 };

 

posted @ 2021-04-02 10:32  谁在写西加加  阅读(30)  评论(0编辑  收藏  举报