LC 109. Convert Sorted List to Binary Search Tree

本文介绍了一种将已排序链表转换为高度平衡二叉搜索树的方法。通过双指针技巧找到中位数作为根节点,递归构造左右子树,确保树的高度平衡。

1.题目描述

109. Convert Sorted List to Binary Search Tree

Medium

73355FavoriteShare

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted linked list: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

给一个上升序列,构造一个“高度平衡”二叉搜索树。所谓“高度平衡”二叉搜素树是指任意一个结点的两个子树高度差不可以大于1.

 

2.解题思路

递归解法比较明显。因为是一个上升序列,所以以中位数为根,左边构造左子树,右边构造右子树即可。稍微需要思考的地方是怎么找这个中位数。上升序列是以链表的形式给出的。看到的一个比较巧妙的方法是两个指针同时从链表头出发,一个每次走两步,另外一个每次走一步。那么走得快的那个到达尾部的时候,走得慢的那个正好在中间,这样就确定了中位数的位置。对前半部分和后半部分进行递归即可。

3.实现代码

/**
 * 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 *sortedListToBST(ListNode *head)
    {
    	return sortedListToBST( head, NULL );
    }
    
    TreeNode *sortedListToBST(ListNode *head, ListNode *tail)
    {
    	if( head == tail )
    		return NULL;
    	if( head->next == tail ) {	
    		TreeNode *root = new TreeNode( head->val );
    		return root;
    	}
    	ListNode *mid = head, *temp = head;
    	while( temp != tail && temp->next != tail ) {// 寻找中间节点,mid走一步,temp走两步,那么temp到达终点的时候mid就是中点了
    		mid = mid->next;
    		temp = temp->next->next;
    	}
    	TreeNode *root = new TreeNode( mid->val );
    	root->left = sortedListToBST( head, mid );
    	root->right = sortedListToBST( mid->next, tail );
    	return root;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值