LeetCode – 897. Increasing Order Search Tree

題目連結:

https://leetcode.com/problems/increasing-order-search-tree/

參考解法:

https://leetcode.com/problems/increasing-order-search-tree/discuss/244939/Swift-88ms

法ㄧ(Two pointers with in-order traversal)

var head: TreeNode?
var prev: TreeNode?
func increasingBST(_ root: TreeNode?) -> TreeNode? {
    guard let root = root else { return nil }
    increasingBST(root.left)
    if head == nil {
    	head = root
  	}
    root.left = nil
    prev?.right = root
    prev = root
    increasingBST(root.right)
    return head
}