Level 1 (day 8)
第一题
题目链接:https://leetcode.cn/problems/validate-binary-search-tree/
个人题解:中序遍历数组有序为BST
代码:
class Solution {
public:
bool isValidBST(TreeNode* root) {
vector<int> ans;
inorder(root,ans);
for(int i=0;i<ans.size()-1;i++)
{
if(ans[i]>=ans[i+1]) return false;
}
return true;
}
void inorder(TreeNode* root,vector<int>& ans)
{
if(!root) return;
inorder(root->left,ans);
ans.push_back(root->val);
inorder(root->right,ans);
}
};
第二题
题目链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/
个人题解:递归
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return NULL;//空返回空
if(root->val==p->val||root->val==q->val) return root;// 示例二
if(root->val<p->val&&root->val<q->val) return lowestCommonAncestor(root->right,p,q);//比他小,向右边
else if(root->val>p->val&&root->val>q->val) return lowestCommonAncestor(root->left,p,q);//比他大,向左边
else return root;
}
};

浙公网安备 33010602011771号