98. 验证二叉搜索树
递归
class Solution {
TreeNode *leftMost;
TreeNode *rightMost;
bool limitYourself(TreeNode *root, int min, int max)
{
if (root == nullptr) {
return true;
}
if (root->val <= min || root->val >= max) {
if (!((root == leftMost && root->val == INT_MIN) || (root == rightMost && root->val == INT_MAX))) {
return false;
}
}
return limitYourself(root->right, root->val, max) && limitYourself(root->left, min, root->val);
}
public:
bool isValidBST(TreeNode *root)
{
leftMost = root;
rightMost = root;
while (leftMost->left != nullptr) {
leftMost = leftMost->left;
}
while (rightMost->right != nullptr) {
rightMost = rightMost->right;
}
return limitYourself(root, INT_MIN, INT_MAX);
}
};
236. 二叉树的最近公共祖先
递归
class Solution {
TreeNode* pp;
TreeNode* qq;
public:
// [ r ] [ p ]
// / \ /
// [ p ] [ q ] [ q ]
TreeNode* giveMeHighestPQ(TreeNode* r) {
if (r == nullptr || r == pp || r == qq) {
return r;
}
auto ll = giveMeHighestPQ(r->left);
auto rr = giveMeHighestPQ(r->right);
if (ll != nullptr) {
if (rr != nullptr) {
return r;
}
return ll;
}
return rr;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
pp = p;
qq = q;
return giveMeHighestPQ(root);
}
};
129. 求根节点到叶节点数字之和
class Solution {
void down(TreeNode* middle, int& ans, int cur) {
int tmp = cur * 10 + middle->val;
if (middle->left == nullptr && middle->right == nullptr) {
ans += tmp;
return;
}
if (middle->left != nullptr) {
down(middle->left, ans, tmp);
}
if (middle->right != nullptr) {
down(middle->right, ans, tmp);
}
}
public:
int sumNumbers(TreeNode* root) {
int ans {};
down(root, ans, 0);
return ans;
}
};
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。