Skip to content

Commit 752feca

Browse files
committed
add: cpp: 7-110
1 parent 1f3c49e commit 752feca

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
// 110: Balanced Binary Tree
2+
// https://leetcode.com/problems/balanced-binary-tree/
3+
4+
#include <iostream>
5+
#include <queue>
6+
#include <vector>
7+
#include <stack>
8+
9+
using namespace std;
10+
11+
struct TreeNode {
12+
int val;
13+
TreeNode *left;
14+
TreeNode *right;
15+
TreeNode() : val(0), left(nullptr), right(nullptr) {}
16+
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
17+
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
18+
};
19+
20+
TreeNode* creator(vector<int> values, TreeNode** root, int i, int n) {
21+
if (n==0) return NULL;
22+
if (i<n) {
23+
TreeNode *temp = new TreeNode(values[i]);
24+
*root = temp;
25+
(*root)->left = creator(values, &((*root)->left), 2*i+1, n);
26+
(*root)->right = creator(values, &((*root)->right), 2*i+2, n);
27+
}
28+
return *root;
29+
};
30+
31+
void createTree(TreeNode** root, vector<int> inputs) {
32+
creator(inputs, root, 0, inputs.size());
33+
}
34+
35+
void showTree(TreeNode* root) {
36+
queue<TreeNode*> q;
37+
vector<vector<int>> result = {};
38+
vector<int> c;
39+
if (root==NULL) { cout << "Empty !" << endl; return; }
40+
q.push(root);
41+
q.push(NULL);
42+
while (!q.empty()) {
43+
TreeNode *t = q.front();
44+
q.pop();
45+
if (t==NULL) {
46+
result.push_back(c);
47+
c.resize(0);
48+
if (q.size() > 0) q.push(NULL);
49+
} else {
50+
c.push_back(t->val);
51+
if (t->left) q.push(t->left);
52+
if (t->right) q.push(t->right);
53+
}
54+
}
55+
56+
cout<<"["; for (auto x : result) {
57+
cout<<"["; for (auto y : x) {
58+
if (!y) { cout << "NULL,"; continue; }
59+
cout<<y<<",";
60+
} cout<<"\b],";
61+
} cout<<"\b]"<<endl;
62+
}
63+
64+
65+
66+
class Solution {
67+
private:
68+
int traverse(TreeNode* root) {
69+
if (root == NULL) return 0;
70+
return max(traverse(root->left), traverse(root->right)) + 1;
71+
}
72+
73+
public:
74+
// SOLUTION
75+
bool isBalanced(TreeNode* root) {
76+
if (root == NULL) return true;
77+
int left = traverse(root->left);
78+
int right = traverse(root->right);
79+
return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
80+
}
81+
};
82+
83+
84+
85+
int main() {
86+
Solution o;
87+
TreeNode* root = NULL;
88+
89+
// INPUT
90+
vector<int> tn = {3,9,20,NULL,NULL,15,7};
91+
createTree(&root, tn);
92+
93+
// OUTPUT
94+
auto result = o.isBalanced(root);
95+
cout << (result ? "true" : "false") << endl;
96+
97+
return 0;
98+
}

0 commit comments

Comments
 (0)