[LeetCode]Convert Sorted List to Binary Search Tree

本文详细介绍了如何使用递归方法将一个有序链表转换为平衡二叉搜索树。通过底向上创建节点并分配给其父节点的方式,确保了树的平衡性。同时,该过程在遍历链表的同时进行,使得操作效率得以提高。
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);
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值