标签:
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; } * } */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { private static ListNode currentHead = null; private TreeNode buildTree(int start, int end) { if (start > end) return null; int mid = start + end >> 1; TreeNode left = buildTree(start, mid-1); TreeNode root = new TreeNode(currentHead.val); root.left = left; currentHead = currentHead.next; root.right = buildTree(mid + 1, end); return root; } public TreeNode sortedListToBST(ListNode head) { if(head == null) return null; currentHead = head; int n = 0; while (head != null) { n++; head = head.next; } return buildTree(0, n-1); } }
LeetCode Convert Sorted List to Binary Search Tree
标签:
原文地址:http://blog.csdn.net/u011345136/article/details/45533471