有序单链表转为二叉树
有序数组转为二叉树
二叉树转为双向有序链表
二叉树转为右子树
class ListNode
{
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class TreeNode
{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution
{
public TreeNode sortedListToBST(ListNode head)
{
if (null == head) return null;
if (null == head.next)
{
return new TreeNode(head.val);
}
ListNode slow = head, fast = head.next.next;
while (fast != null && fast.next != null)
{
fast = fast.next.next;
slow = slow.next;
}
TreeNode node = new TreeNode(slow.next.val);
node.right = sortedListToBST(slow.next.next);
slow.next = null;
node.left = sortedListToBST(head);
return node;
}
}