【LeetCode】Convert Sorted List to Binary Search Tree

链表转平衡二叉搜索树

题目:Convert Sorted List to Binary Search Tree


<span style="font-size:18px;">/**LeetCode convert link-list to Binary Search Tree
 *题意:给定一个按照升序排列的链表,要求将其转化为一个高度平衡的二查搜索树
 *思路:因为链表是升序排列的,所以转化为二叉搜索树是简单的,但是要求是平衡的,即左右子数的高度 差在1之内
 *可以取中间的点为根节点,保证两边数量是一样的,这样递归下来就能得到平衡的二叉树
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
package javaTrain;

public class Train19 {
	public TreeNode sortedListToBST(ListNode head) {
		if(head == null) return null;
        ListNode pre = head;		//用于找到中间的节点
        ListNode last = head;
        TreeNode root;;
		if(head.next == null){
			root = new TreeNode(head.val);
			root.left = null;
			root.right = null;
			return root;
		}
        while(pre != null && pre.next != null){	//找到中间节点
        	pre = pre.next.next;
        	last = last.next;
        } 
        root = new TreeNode(last.val);
        ListNode newHead = last.next;
        last.next = null;
        root.left = sortedListToBST(head);
        root.right = sortedListToBST(newHead);
        return root;
    }
}
</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值