struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
//We create nodes bottom-up, and assign them to its parents.
//The bottom-up approach enables us to access the list in its order while creating nodes.
public:
//note: because we use the method bottom to up, so the change of head must be along the way down
//when back to current level, the head is in the right place
TreeNode* Convert2BST(ListNode*& head, int start, int end)
{
if(start > end)
return NULL;
int mid = (start+end)/2;
TreeNode* left = Convert2BST(head, start, mid-1);
TreeNode* parent = new TreeNode(head->val);//bottom-up, so the assign should be put here
parent->left = left;
head = head->next;//one valid element is visited, so should point to next, because of bottom-up
parent->right = Convert2BST(head, mid+1, end);
return parent;
}
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = 0;
ListNode* p = head;
while(p)
{
n++;
p = p->next;
}
//then divide and conquer
return Convert2BST(head, 0, n-1);
}
};
second time
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedListToBSTUtil(ListNode*& cur, int start, int end)
{
if(start > end) return NULL;
int mid = start+(end-start)/2;
TreeNode* left = sortedListToBSTUtil(cur, start, mid-1);
TreeNode* root = new TreeNode(cur->val);
cur = cur->next;
TreeNode* right = sortedListToBSTUtil(cur, mid+1, end);
root->left = left;
root->right = right;
return root;
}
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int cnt = 0;
ListNode* p = head;
while(p != NULL) p = p->next, cnt++;
return sortedListToBSTUtil(head, 0, cnt-1);
}
};
本文详细介绍了如何使用递归方法将一个有序链表转换为平衡二叉搜索树。通过底向上创建节点并分配给其父节点的方式,确保了树的平衡性。同时,该过程在遍历链表的同时进行,使得操作效率得以提高。
412

被折叠的 条评论
为什么被折叠?



