LeetCode 109. 有序链表转换二叉搜索树 题解+测试 C/C++

主要思路

构造平衡的二叉搜索树:首先使用快慢指针法找到中位数,作为根节点,然后递归构造左子树与右子树

#include <iostream>
#include <cstdio>
using namespace std;
#include <queue>


struct ListNode {
	int val;
	ListNode *next;
	ListNode():val(0),next(nullptr){}
	ListNode(int x):val(x),next(nullptr){}
	ListNode(int x,ListNode *next):val(x),next(next){}
};

struct TreeNode
{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode():val(0),left(nullptr),right(nullptr){}
	TreeNode(int x):val(x),left(nullptr),right(nullptr){}
	TreeNode(int x,TreeNode *left,TreeNode *right):val(x),left(left),right(right){}
	
};


class Solution{
public:
	//快慢指针获取中位数
	ListNode *getMedian(ListNode *left,ListNode *right) {
		ListNode *fast = left;
		ListNode *slow = left;
		while(fast!=right&&fast->next!=right) {
			fast = fast->next;//fast走两步  slow走一步
			fast = fast->next;
			slow = slow->next;
		}
		return slow;
	}

	TreeNode *buildTree(ListNode *left,ListNode *right) {
		if(left==right) {
			return nullptr;
		}
		ListNode *mid = getMedian(left,right);
		TreeNode *root = new TreeNode(mid->val);
		root->left = buildTree(left,mid);
		root->right = buildTree(mid->next,right);
		return root;
	}

	TreeNode *sortedListToBST(ListNode *head) {
		return buildTree(head,nullptr);
	}
};

/**********测试用***********/
ListNode *createList(int a[],int n) {
	ListNode *head = nullptr,*p = nullptr;
	for(int i = 0;i<n;i++) {
		if(head==nullptr) {
			head = p = new ListNode(a[i]);

		}
		else {
			p->next = new ListNode(a[i]);
			p = p->next;
		}
	}
	return head;
}

void printList(ListNode *h) {
	while(h!=nullptr) {
		printf("%d -> ",h->val);
		h = h->next;
	}
	printf("null\n");
}


//层次遍历打印bst
void printTree_level_order(TreeNode *root) {
	queue<TreeNode *> que;
	que.push(root);
	while(que.size()>0) {
		TreeNode *tn = que.front();
		que.pop();
		if(tn==nullptr) {
			printf("null ");
			continue;
		}
		printf("%d ",tn->val);
		que.push(tn->left);
		que.push(tn->right);
	}
	printf("\n");
}


int main() {

	int a[] = {-10,-3,0,5,9};
	Solution sol;
	ListNode *head = createList(a,sizeof(a)/sizeof(int));
	printf("list:\n");
	printList(head);
	printf("BST:\n");
	TreeNode *root = sol.sortedListToBST(head);
	printTree_level_order(root);


	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值