LeetCode 109. Convert Sorted List to Binary Search Tree

LeetCode 109. Convert Sorted List to Binary Search Tree

题目来源:https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/description/

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:将链表转化为数组后,再转化为二叉搜索树

public TreeNode sortedListToBST(ListNode head) {
        if(head==null)
            return null;
        int len=0,i=0;
        ListNode p=head;
        while(p.next!=null){
            len++;
            p=p.next;
        }
        int a[]=new int[len];
        while(head.next!=null){
            a[i++]=head.val;
            head=head.next;
        }
        TreeNode root=CreatBST(a, 0, len-1);
        return root;
    }

    public TreeNode CreatBST(int []nums,int left,int right){
        if(left>right)
            return null;
        int mid=(left+right)/2;
        TreeNode node=new TreeNode(nums[mid]);
        node.left=CreatBST(nums, left, mid-1);
        node.right=CreatBST(nums, mid+1,right);
        return node;
    }

思路2:利用快慢指针,找到链表中点所在位置(经常用的一种方式),将每次二分查找得到的链表中点递归插入;

public TreeNode sortedListToBST(ListNode head) {
          if(head==null)
              return null;
         return  CreatBST(head,null);
      }
      public TreeNode CreatBST(ListNode head,ListNode tail){
          ListNode slow=head;
          ListNode fast=head;
          if(head==tail)
              return null;      //不加这句话,产生栈溢出,如果没有返回空的语句,递归不会结束。
          while(fast!=tail&&fast.next!=tail){
              slow=slow.next;
              fast=fast.next.next;
          }
          TreeNode root =new TreeNode(slow.val);      //通过快慢指针的方式找到链表的中点slow
          root.left=CreatBST(head, slow);
          root.right=CreatBST(slow.next, tail);
          return root;
      }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值