426. Convert Binary Search Tree to Sorted Doubly Linked List

/**
 * 426. Convert Binary Search Tree to Sorted Doubly Linked List
 * https://www.lintcode.com/problem/convert-binary-search-tree-to-sorted-doubly-linked-list/description
 * */
class Solution {
    //save last access node
    var prev: TreeNode? = null

    fun treeToDoublyList(root: TreeNode?): TreeNode? {
        if (root == null) {
            return null
        }
        //the leftmost node
        val dummy = TreeNode(-1)
        //these two node point to the same
        prev = dummy
        inorder(root)
        //link each other
        val head = dummy.right
        prev?.right = head
        head?.left = prev
        return head
    }

    //changing prev
    private fun inorder(node: TreeNode?) {
        if (node == null) {
            return
        }
        inorder(node.left)
        //link each other
        prev?.right = node
        node.left = prev
        prev = node
        inorder(node.right)
    }
}

 

posted @ 2020-03-24 14:47  johnny_zhao  阅读(89)  评论(0编辑  收藏  举报