有序单链表转为平衡二叉树


有序单链表转为二叉树
有序数组转为二叉树

二叉树转为双向有序链表

二叉树转为右子树

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;
    }
}

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/zhangbaoanhadoop/article/details/79833823
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞