luoheng
10/11/2019 - 10:46 AM

increasingBST

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

func midOrder(root *TreeNode) (head, tail *TreeNode) {
    if root.Left == nil && root.Right == nil {
        return root, root
    }
    head, tail = root, root
    var h, t *TreeNode
    if root.Left != nil {
        head, t = midOrder(root.Left)
        t.Right, root.Left = root, nil
    }
    if root.Right != nil {
        h, tail = midOrder(root.Right)
        root.Right, h.Left = h, nil
    }
    return
}

func increasingBST(root *TreeNode) *TreeNode {
    if root == nil {
        return nil
    }
    head, _ := midOrder(root)
    return head
}