Convert Sorted Array to Binary Search Tree & Convert Sorted List to Binary Search Tree

Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

方法:将有序数组转为平衡二叉树,我们知道平衡二叉树的中序遍历是有序数组,而且“中间”的元素可以作为根节点,那么构建树的时候,找出中间元素,构造根元素,然后继续重复上面的方法,构造左子树和右子树。代码如下:

 1 /**
 2  * Definition for binary tree
 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 class Solution {
11 public:
12     TreeNode *sortedArrayToBST(vector<int> &num) {
13         TreeNode* root = 0;
14         constructBST(num, 0, num.size()-1, root);
15         return root;
16     }
17
18     void constructBST(vector<int>& num, int ibegin, int iend, TreeNode*& root) {    //root是引用
19         if(ibegin > iend) return;
20         int mid = ibegin + (iend-ibegin)/2; //取中间的元素
21         root = new TreeNode(num[mid]);  //建立根节点
22         constructBST(num, ibegin, mid-1, root->left);   //构建左子树
23         constructBST(num, mid+1, iend, root->right);    //构建右子树
24     }
25 };

Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

方法同上,不过这次是单链表不是数组,那么可以设置快慢指针,快指针每次走两步,慢指针每次走一步,找出中间节点,继而构造根节点,继续上面的步骤,构造左子树和右子树,代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 /**
10  * Definition for binary tree
11  * struct TreeNode {
12  *     int val;
13  *     TreeNode *left;
14  *     TreeNode *right;
15  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
16  * };
17  */
18 class Solution {
19 public:
20     TreeNode *sortedListToBST(ListNode *head) {
21         TreeNode* root = 0;
22         constructBST(head, root);
23         return root;
24     }
25
26     void constructBST(ListNode* head, TreeNode*& root) {
27         if( !head ) return ;    //如果链表为空,则说明子树为空
28         ListNode* pre = 0;  //slow的前驱节点
29         ListNode* fast = head;  //快指针,每次走两步
30         ListNode* slow = head;  //慢指针,每次走一步
31         while( fast && fast->next ) {
32             fast = fast->next->next;
33             pre = slow;
34             slow = slow->next;
35         }
36         ListNode* lhead = 0;        //新左链表
37         ListNode* rhead = slow->next;   //新右链表
38         ListNode* midNode = slow;       //中间节点
39         midNode->next = 0;
40         if( pre ) {    //如果新左链表不为空的情况
41             lhead = head;
42             pre->next = 0;
43         }
44         root = new TreeNode(midNode->val);  //利用中间元素构建根节点
45         delete midNode;
46         constructBST(lhead, root->left);    //构建左子树
47         constructBST(rhead, root->right);   //构建右子树
48     }
49 };
时间: 2024-08-01 10:44:22

Convert Sorted Array to Binary Search Tree & Convert Sorted List to Binary Search Tree的相关文章

leetcode 26. Remove Duplicates from Sorted Array 、80. Remove Duplicates from Sorted Array II

两个题类似,第一个题是不允许有重复的数字,第二个题是允许每个数字最多重复两个,两个题目都要求在原数组上进行操作,并返回生成数组的长度,即空间复杂度为O(1). 两个题都是使用双指针,第一个指针指向生成新的数组的最后一个位置,第二个指针指向当前进行判断的位置. 唯一不同的是, 第二个题需要设置一个变量来控制重复的个数是否超过2 26. Remove Duplicates from Sorted Array class Solution { public: int removeDuplicates(

62. Search in Rotated Sorted Array【medium】

62. Search in Rotated Sorted Array[medium] Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, ot

81. Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":What if duplicates are allowed? Would this affect the run-time complexity? How and why? Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4

leetcode 6. 在有序数组旋转后搜索 Search in Rotated Sorted Array

Search in Rotated Sorted Array 难度:Hard Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherw

&lt;LeetCode OJ&gt; Find Minimum in Rotated Sorted Array【153】

153. Find Minimum in Rotated Sorted Array My Submissions Question Total Accepted: 73048 Total Submissions: 209952 Difficulty: Medium Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7

26. Remove Duplicates from Sorted Array【easy】

26. Remove Duplicates from Sorted Array[easy] Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with consta

leetCode-数组:Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array:从排列后的数组中删除重复元素 考察数组的基本操作: class Solution { public int removeDuplicates(int[] nums) { if (nums==null || nums.length==0) return 0; int index = 1; for(int i =1; i<nums.length; i++){ if(nums[i]!=nums[i-1]){ nums[index]

LeetCode OJ - Convert Sorted Array/List to Binary Search Tree

虚函数使用的时机 为什么虚函数不总是适用? 1. 虚函数有事会带来很大的消耗: 2. 虚函数不总是提供所需的行为: 3. 当我们不考虑继承当前类时,不必使用虚函数. 必须使用虚函数的情况: 1. 当你想删除一个表面上指向基类对象,实际却是指向派生类对象的指针,就需要虚析构函数. LeetCode OJ - Convert Sorted Array/List to Binary Search Tree,布布扣,bubuko.com LeetCode OJ - Convert Sorted Arra

leetcode 108 Convert Sorted Array to Binary Search Tree

题目连接 https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ Convert Sorted Array to Binary Search Tree Description Given an array where elements are sorted in ascending order, convert it to a height balanced BST. /** * Definition f

39.1: Convert Sorted Array to Binary Search Tree

/************************************************************************/            /*       39.1:  Convert Sorted Array to Binary Search Tree                               */            /************************************************************