Leetcode二叉搜索树习题集
98. Validate Binary Search Tree
class Solution { public: bool isValidBST(TreeNode* root) { return dfs(root,NULL,NULL); }
// 此处要最大最小是因为BST需要比较的是全局的最大最小 bool dfs(TreeNode* root, TreeNode* Min, TreeNode* Max){ if(root==NULL) return true; if(Min!=NULL && Min->val>=root->val) return false; if(Max!=NULL && Max->val<=root->val) return false; return dfs(root->left,Min,root) && dfs(root->right,root,Max); } };
100. Same Tree
class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if(p==NULL && q==NULL) return true; if(p==NULL || q==NULL) return false; if(p->val != q->val) return false; return isSameTree(p->left,q->left) && isSameTree(p->right,q->right); } };
700. Search Tree
class Solution { public: TreeNode* searchBST(TreeNode* root, int val) { if(root==NULL) return NULL; if(root->val == val) return root; else if(root->val < val) return searchBST(root->right,val); else return searchBST(root->left,val); } };
701. Insert Node
class Solution { public: TreeNode* insertIntoBST(TreeNode* root, int val) { if(root==NULL) return new TreeNode(val); // 如果找到合适的位置,直接在此处新建一个节点 if(root->val<val) root->right = insertIntoBST(root->right,val); else root->left = insertIntoBST(root->left,val); return root; } };
Delete Node
class Solution { public: TreeNode* deleteNode(TreeNode* root, int key) { if(root==NULL) return NULL; if(root->val == key){ // 如果只有一个节点或者直接没有节点了 if(root->left==NULL) return root->right; if(root->right==NULL) return root->left; // 如果两个子节点都有,找到右数的最小节点拿过来删 TreeNode* minNode = getMin(root->right); root->val = minNode->val; // 替换完值后再右数继续删除最小的那个值 root->right = deleteNode(root->right,minNode->val); } else if(root->val > key){ root->left = deleteNode(root->left,key); } else { root->right = deleteNode(root->right,key); } return root; } TreeNode* getMin(TreeNode* node){ while(node->left!=NULL) node = node->left; return node; } };
浙公网安备 33010602011771号