目录
状态:没有思路,还是236的套路。
利用二叉搜索树的特性进行分析,不需要对中间节点进行操作,所以没办法区分前/中/后序遍历。
- class Solution {
- public:
- TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
- if(root->val > p->val && root->val > q->val){
- return lowestCommonAncestor(root->left, p, q);
- }else if(root->val < p->val && root->val < q->val){
- return lowestCommonAncestor(root->right, p, q);
- }else return root;
- }
- };
- class Solution {
- public:
- TreeNode* insertIntoBST(TreeNode* root, int val) {
- if(root == nullptr){
- TreeNode* node = new TreeNode(val);
- return node;
- }
- if(root->val > val) root->left = insertIntoBST(root->left, val);
- if(root->val < val) root->right = insertIntoBST(root->right, val);
- return root;
- }
- };
状态:比上一题复杂得多
介绍一个二叉树的通用方法
- class Solution {
- public:
- TreeNode* deleteNode(TreeNode* root, int key) {
- // 二叉树通用法
- if(root == nullptr) return root;
- if(root->val == key){
- if(root->right == nullptr){
- return root->left;
- }
- TreeNode* cur = root->right;
- while(cur->left){
- cur = cur->left;
- }
- swap(root->val, cur->val);
- }
- root->left = deleteNode(root->left, key);
- root->right = deleteNode(root->right, key);
- return root;
- }
- };