BST
LC108,将有序数组转化为BST
则中序遍历BST,可以化为有序数组。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums) { return dfs(nums,0,nums.size()-1); } TreeNode* dfs(vector<int>nums,int left,int right) { if(right<left) return nullptr; int mid=left+(right-left)/2; TreeNode* root=new TreeNode(nums[mid]); root->left=dfs(nums,left,mid-1); root->right=dfs(nums,mid+1,right); return root; } };
LC700
class Solution { public: TreeNode* searchBST(TreeNode* root, int val) { if (root == nullptr) { return nullptr; } if (root->val == val) { return root; } else if (root->val > val) { // 在左子树中查找 return searchBST(root->left, val); } else { // 在右子树中查找 return searchBST(root->right, val); } } };
LC701
不过这种插入会破坏平衡性
递归:
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* insertIntoBST(TreeNode* root, int val) { TreeNode* node = new TreeNode(val); if (root == nullptr) { return node; } TreeNode* cur = root; while (true) { if (cur->val > val) { if (cur->left == nullptr) { cur->left = node; break; } cur = cur->left; } else { if (cur->right == nullptr) { cur->right = node; break; } cur = cur->right; } } return root; } };
LC450
class Solution { public: TreeNode* deleteNode(TreeNode* root, int key) { if(root==nullptr) return root; //1 没有找到 if(root->val == key){ //2 左右孩子都为空 //3 左孩子为空,右孩子不为空 if(root->left==nullptr) return root->right; //4 右孩子为空,左孩子不为空 else if(root->right==nullptr) return root->left; //5 左右都不为空,将删除节点的左子树放到删除节点的右子树的最左边节点的左孩子上,返回节点右孩子为新的根 else{ TreeNode* cur=root->right; while(cur->left!=nullptr) cur=cur->left; cur->left=root->left; TreeNode* tmp=root; root=root->right; delete tmp; return root; } } if(root->val>key) root->left=deleteNode(root->left,key); if(root->val<key) root->right=deleteNode(root->right,key); return root; } };