leetcode: convert-sorted-list-to-binary-search-tree

题目描述:

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

解题思路:

  1. 首先理解题意,这道题的意思就是说将一个升序排列的链表转换成一个高度平衡的二叉树
  2. 对于平衡二叉树我们脑子里的第一个反应应该就是递归了
  3. 这题也不例外,我们首先找到链表中间位置的节点,将它设为根节点,然后递归处理它的左右节点

代码如下:

    public TreeNode sortedListToBST(ListNode head) {
	
	// 首先处理链表的特殊情况,同时也是递归的终止条件
        if(head == null) return null;
        if(head.next == null) return new TreeNode(head.val);

        ListNode fast = head.next;
        ListNode slow = head;

	// 找到链表的中间节点
        while(fast.next != null && fast.next.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }

	// 递归处理链表中的节点,将其建成树形结构
        TreeNode root = new TreeNode(slow.next.val);
        root.right = sortedListToBST(slow.next.next);
        slow.next = null;
        root.left = sortedListToBST(head);

        return root;
    }

转载于:https://my.oschina.net/happywe/blog/3083882

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值