leetcodeSolution to some Leetcode problems written in C++ |
git clone git://git.dimitrijedobrota.com/leetcode.git |
Log | Files | Refs | README | LICENSE |
0110.cpp (749B)
0 class Solution {
1 public:
2 bool isBalanced(TreeNode *root) {
3 if (!root) return true;
4 stack<TreeNode *> st;
5 st.push(root);
6 while (!st.empty()) {
7 TreeNode *root = st.top();
8 if (root == nullptr) {
9 st.pop(), root = st.top(), st.pop();
10 int left = root->left ? root->left->val : 0;
11 int right = root->right ? root->right->val : 0;
12 if (abs(right - left) > 1) return false;
13 root->val = max(left, right) + 1;
14 continue;
15 }
16 st.push(nullptr);
17 if (root->left) st.push(root->left);
18 if (root->right) st.push(root->right);
19 }
20 return true;
21 }
22 };