Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
用空间换时间的方法,先用一个数组将节点按序存放,然后建树,代码如下:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; next = null; } * } */ /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private List<TreeNode> list = new ArrayList<TreeNode>(); public TreeNode creatBST(int low,int high) { if(low<=high) { int mid = (high+low)/2; TreeNode root = list.get(mid); root.left = creatBST(low,mid-1); root.right = creatBST(mid+1,high); return root; } else return null; } public TreeNode sortedListToBST(ListNode head) { while(head!=null) { TreeNode node = new TreeNode(head.val); list.add(node); head = head.next; } return creatBST(0,list.size()-1); } }