Convert Sorted List to Binary Search Tree --- LeetCode

来源:互联网 发布:永恒之塔女性捏脸数据 编辑:程序博客网 时间:2024/06/06 08:50

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



解题思路:中序递归遍历构造,每次遍历找到中间节点即为根节点,左边为左子树,右边为右子树。

public class Solution {
    public TreeNode search(ListNode head,int left,int right){
     TreeNode node=null;
     if(left>right){
    return null;
     }
     int index=(left+right)/2;
     ListNode middle=head;
     for(int i=left;i<index;i++){
     middle=middle.next;       
     }
     node=new TreeNode(middle.val);
     node.left=search(head,left,index-1);
     node.right=search(middle.next,index+1,right);
     return node;
}

    public TreeNode sortedListToBST(ListNode head) {
          TreeNode root=null;
     if(head==null){
    return root; 
     }
     ListNode node=head;
     int count=1;
     while(node.next!=null){      
     node=node.next;
     count++;
     }
     root=search(head,1,count);
          return root;
    }
}

0 0
原创粉丝点击