有序数组转换二叉搜索树
题目描述
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
给定列表是有序列表,找到列表中的中间元素作为二叉搜索树的根,该点左侧的所有元素递归的去构造左子树,同理右侧的元素构造右子树。这必然能够保证最后构造出的二叉搜索树是平衡的。所以用二分法每次查找当前序列中的中间元素作为根结点,构造平衡二叉树。
代码(c++)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& nums,int l,int r){
if(l>r) return NULL;
int mid=(l+r)/2;
TreeNode* root=new TreeNode(nums[mid]);
root->left=buildTree(nums,l,mid-1);
root->right=buildTree(nums,mid+1,r);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
return buildTree(nums,0,nums.size()-1);
}
};
有序链表转换二叉搜索树
题目描述
给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
因为给定序列有序,所以这个序列对应着平衡二叉树的中序遍历序列,于是模拟中序遍历:每次遍历完左子树返回到根时,创建根结点,值为此时链表头结点的值,然后链表指针移到下一个结点,作为下一个子树的根结点,接着再遍历右子树。
(还有一种思路就是将链表中数据转存到数组中,用上一题(有序数组转换二叉搜索树)的方法做)
代码(c++)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(int start,int end,ListNode* &head){
if(start>end) return NULL;
int mid=(start+end)/2;
TreeNode* l=buildTree(start,mid-1,head);
TreeNode* root=new TreeNode(head->val);
head=head->next;
root->left=l;
root->right=buildTree(mid+1,end,head);
return root;
}
TreeNode* sortedListToBST(ListNode* head) {
if(head==NULL) return NULL;
ListNode* temp=head;
TreeNode* res;
int len=0;
while(temp!=NULL){
temp=temp->next;
len+=1;
}
temp=head;
return buildTree(0,len-1,temp);
}
};