标签:链表
题目
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 { public TreeNode sortedListToBST(ListNode head) { if(head==null){ return null; } ListNode cur=head; int count=0; while(cur!=null){ cur=cur.next; count++; } List<ListNode> list=new ArrayList<ListNode>(); list.add(head); return helper(list,0,count-1); } private TreeNode helper(List<ListNode> list,int l,int r){ if(l>r){ return null; } int m=(l+r)/2; TreeNode left=helper(list,l,m-1); //设置左子树 TreeNode root=new TreeNode(list.get(0).val); //设置当前节点作为根 root.left=left; list.set(0,list.get(0).next); root.right=helper(list,m+1,r); return root; } }
---EOF---
【LeetCode】Convert Sorted List to Binary Search Tree
标签:链表
原文地址:http://blog.csdn.net/navyifanr/article/details/41897713