1.二叉搜索树
二叉搜索树的中序遍历是一个升序序列(左子树结点的值比根结点的值都小,右子树的值比根结点的值都大)
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1
所以:根结点是有序数组正中间的一个数,使用递归分别求出左子树和右子树
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size()==0) return nullptr;
if(nums.size()==1) return new TreeNode(nums[0]);
int mid=nums.size()/2;
TreeNode* root=new TreeNode(nums[mid]);
vector<int> l(nums.begin(),nums.begin()+mid);
vector<int> r(nums.begin()+mid+1,nums.end());
root->left=sortedArrayToBST(l);
root->right=sortedArrayToBST(r);
return root;
}
};
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
先把链表转化成数组,然后和上题一样
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
if(head==nullptr) return nullptr;
if(head->next==nullptr) return new TreeNode(head->val);
vector<int> nums;
ListNode* p=head;
while(p!=nullptr){
nums.push_back(p->val);
p=p->next;
}
return dfs(nums);
}
TreeNode* dfs(vector<int> nums){
if(nums.size()==0) return nullptr;
if(nums.size()==1) return new TreeNode(nums[0]);
int mid=nums.size()/2;
vector<int> l(nums.begin(),nums.begin()+mid);
vector<int> r(nums.begin()+mid+1,nums.end());
TreeNode* root=new TreeNode(nums[mid]);
root->left=dfs(l);
root->right=dfs(r);
return root;
}
};
设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)
二分法,若根结点比p小,则下一结点在右子树
若和p相同,则下一结点在右子树
若比p大,则
下一结点在左子树
没有左子树,则根节点就是p的下一结点
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
if(root==nullptr) return nullptr;
if(root->val<=p->val)
return inorderSuccessor(root->right,p);
else{
TreeNode* ans=inorderSuccessor(root->left,p);
if(ans==nullptr) return root;
return ans;
}
}
};