- Validate Binary Search Tree
solution
class Solution {
public:
bool isValidBST(TreeNode* root) {
return isValidBST(root, LONG_MIN, LONG_MAX);
}
bool isValidBST(TreeNode* root, long mn, long mx) {
if (!root) return true;
if (root->val <= mn || root->val >= mx) return false;
return isValidBST(root->left, mn, root->val) && isValidBST(root->right, root->val, mx);
}
};
result
- Binary Tree Level Order Traversal
solution
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<TreeNode*> que;
que.push(root);
while(que.size()!=0){
vector<int> tmpRes;
queue<TreeNode*> tmpQue;
while(que.size()!=0){
TreeNode *node = que.front();
que.pop();
if(node->left) tmpQue.push(node->left);
if(node->right) tmpQue.push(node->right);
tmpRes.push_back(node->val);
}
res.push_back(tmpRes);
que = tmpQue;
}
// reverse(res.begin(),res.end());
return res;
}
};
result
- Binary Tree Level Order Traversal II
solution
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<TreeNode*> que;
que.push(root);
while(que.size()!=0){
vector<int> tmpRes;
queue<TreeNode*> tmpQue;
while(que.size()!=0){
TreeNode *node = que.front();
que.pop();
if(node->left) tmpQue.push(node->left);
if(node->right) tmpQue.push(node->right);
tmpRes.push_back(node->val);
}
res.push_back(tmpRes);
que = tmpQue;
}
reverse(res.begin(),res.end());
return res;
}
};
result
resources:
https://en.wikipedia.org/wiki/Binary_tree
https://www.geeksforgeeks.org/binary-tree-data-structure/
https://www.youtube.com/watch?v=H5JubkIy_p8
https://www.youtube.com/watch?v=bD9oYzwfZ1w