1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 11 class Solution { 12 public: 13 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 14 while(root){ 15 if(p->val > root->val && q->val > root->val) root = root->right; 16 else if(p->val < root->val && q->val < root->val) root = root->left; 17 else return root; 18 } 19 return root; 20 } 21 };
先查找符合条件的叶子结点,然后根据大小在这个节点下插入
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 TreeNode* deleteNode(TreeNode* root, int key) { 15 if(root == nullptr) return nullptr; 16 if(root->val == key){ 17 if(root->left == nullptr) return root->right; 18 if(root->right == nullptr) return root->left; 19 TreeNode* result = root->left; 20 TreeNode* pre = root->left; 21 while(pre->right){ 22 pre = pre->right; 23 } 24 pre->right = root->right; 25 return result; 26 } 27 if(root->left == nullptr && root->right == nullptr && root->val != key){ 28 return root; 29 } 30 if(root->val > key){ 31 root->left = deleteNode(root->left, key); 32 }else{ 33 root->right = deleteNode(root->right, key); 34 } 35 return root; 36 } 37 };
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 TreeNode* insertIntoBST(TreeNode* root, int val) { 15 if(root == nullptr) return new TreeNode(val); 16 TreeNode* pre; 17 TreeNode* result = root; 18 while(root){ 19 pre = root; 20 if(root->val > val){ 21 root = root->left; 22 }else{ 23 root = root->right; 24 } 25 } 26 if(val > pre->val) pre->right = new TreeNode(val); 27 else pre->left = new TreeNode(val); 28 return result; 29 } 30 };
浙公网安备 33010602011771号