比较简单的递归题目,找到中间节点后递归左右两部分作为左右子树就可以了。
public TreeNode sortedListToBST(ListNode head) { if(head == null) return null; else if(head.next == null) return new TreeNode(head.val); int n = 0; ListNode dummy = new ListNode(0); dummy.next = head; ListNode temp1 = head; while(temp1 != null) { temp1 = temp1.next; n++; } n = (n+1) / 2; ListNode temp2 = dummy; temp1 = head; while(n > 1) { temp2 = temp2.next; temp1 = temp1.next; n--; // don't forget to write this! } temp2.next = null; // safe TreeNode root = new TreeNode(temp1.val); root.left = sortedListToBST(dummy.next); root.right = sortedListToBST(temp1.next); return root; }
没有评论:
发表评论