Convert Sorted List to Binary Search Tree

来源:互联网 发布:知乎格林德沃x邓布利多 编辑:程序博客网 时间:2024/06/06 00:24

Given a singly linked list where elements are sorted in ascending order, convert it 

to a height balanced BST.

从下往上,从左往右构造二叉树。

static ListNode h;public TreeNode sortedListToBST(ListNode head) {h = head;int len = 0;ListNode p = head;while (p != null) {len++;p = p.next;}return sortedListToBST(len);}public TreeNode sortedListToBST(int size) {if (size<=0)return null;TreeNode left = sortedListToBST(size/2);TreeNode root = new TreeNode(h.val);h = h.next;TreeNode right = sortedListToBST(size-1-size/2);root.left = left;root.right = right;return root;}


0 0