/** * 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) } }