【LeetCode】C# 109、Convert Sorted List to Binary Search Tree

来源:互联网 发布:js中sleep怎么使用 编辑:程序博客网 时间:2024/06/05 20:57

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

题意:给定一个升序单向链表,将其转化为以一个高度平衡的查询二叉树。
思路:跟上题一样,由递归思路每次找中数作为根,其左右边的链表分别作为左右子树。多出来的问题在于怎样找到中位数。可以通过新建slow、fast两个节点遍历一次链表段来找出。

/** * Definition for singly-linked list. * public class ListNode { *     public int val; *     public ListNode next; *     public ListNode(int x) { val = x; } * } *//** * Definition for a binary tree node. * public class TreeNode { *     public int val; *     public TreeNode left; *     public TreeNode right; *     public TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode SortedListToBST(ListNode head) {        if(head == null) return null;        return toBST(head,null);    }    public TreeNode toBST(ListNode tree,ListNode list){        ListNode slow = tree;        ListNode fast = tree;        if(tree==list) return null;        while(fast!=list&&fast.next!=list){        fast = fast.next.next;        slow = slow.next;        }        TreeNode thead = new TreeNode(slow.val);        thead.left = toBST(tree,slow);        thead.right = toBST(slow.next,list);        return thead;    }}
阅读全文
0 0
原创粉丝点击