class Solution {
public:
vector<vector<int>>res;
void dfs(TreeNode* root, queue<TreeNode*>q, vector<int>path) {
if(!root) return;
if(root->left) q.push(root->left);
if(root->right) q.push(root->right);
if(q.empty()) {
res.push_back(path);
return;
}
int n = q.size();
while(n --) {
TreeNode* cur = q.front(); q.pop();
path.push_back(cur->val);
dfs(cur, q, path);
q.push(cur);
path.pop_back();
}
}
vector<vector<int>> BSTSequences(TreeNode* root) {
if(root == NULL) return {{}};
queue<TreeNode*>q;
vector<int>path;
path.push_back(root->val);
dfs(root, q, path);
return res;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left == NULL) return right;
if(right == NULL) return left;
return root;
}
};
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if(!root || !p) return NULL;
if(p->val >= root->val) {
return inorderSuccessor(root->right, p);
} else {
TreeNode* left = inorderSuccessor(root->left, p);
return left ? left : root;
}
}
};
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root == NULL) return true;
TreeNode*maxLeft = root->left, *minRight = root->right;
while(maxLeft != NULL && maxLeft->right != NULL) {
maxLeft = maxLeft->right;
}
while(minRight != NULL && minRight->left != NULL) {
minRight = minRight->left;
}
bool res = (maxLeft == NULL || maxLeft->val < root->val) && (minRight == NULL || minRight->val > root->val);
return res && isValidBST(root->left) && isValidBST(root->right);
}
};
class Solution {
public:
int depth(TreeNode* root) {
if(root == NULL) return 0;
int left = depth(root->left);
int right = depth(root->right);
return max(left, right) + 1;
}
bool isBalanced(TreeNode* root) {
if(!root) return true;
if(abs(depth(root->left) - depth(root->right)) < 2) {
return isBalanced(root->left) && isBalanced(root->right);
}
return false;
}
};