Leetcode: Increasing Order Search Tree

Increasing Order Search Tree



Similar Problems:


Given a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.

Example 1:

Input: [5,3,6,2,4,null,8,1,null,null,null,7,9]

       5
      / \
    3    6
   / \    \
  2   4    8
 /        / \ 
1        7   9

Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

 1
  \
   2
    \
     3
      \
       4
        \
         5
          \
           6
            \
             7
              \
               8
                \
                 9  

Note:

  1. The number of nodes in the given tree will be between 1 and 100.
  2. Each node will have a unique integer value from 0 to 1000.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// Blog link: https://code.dennyzhang.com/increasing-order-search-tree
// Basic Ideas: in-order
// Complexity: Time O(n), Space O(n)
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
type LinkNode struct {
  Head *TreeNode
  Tail *TreeNode
}

func dfs(root *TreeNode) *LinkNode {
    if root == nil { return &LinkNode{nil, nil} }
    if root.Left == nil && root.Right == nil {
        return &LinkNode{root, root}
    }
    l1 := dfs(root.Left)
    l2 := dfs(root.Right)

    if l1.Tail != nil {
        l1.Tail.Right = root
    }
    root.Left, root.Right = nil, l2.Head
    head, tail := l1.Head, l2.Tail
    if head == nil { head = root }
    if tail == nil { tail = root }
    return &LinkNode{head, tail}
}
func increasingBST(root *TreeNode) *TreeNode {
    return dfs(root).Head
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.