Friday, October 06, 2017

flatten binary tree to right

Flatten to node's right pointers only.
    1
   / \
  2   5
 / \   \
3   4   6


 1
  \
   2
    \
     3
      \
       4
        \
         5
          \
           6
(n):
    if n == null:
        return
    if n.left != null:
        lsubtree = n.left
        rsubtree = n.right
        n.left = n.right = null
        n.right = lsubtree
        // rightmost of left subtree
        rmost = lsubtree
        while rmost.right != null:
            rmost = rmost.right
        rmost.right = rsubtree
    (n.right)
(n):
    while n != null:
        if n.left != null:
            lsubtree = n.left
            rsubtree = n.right
            n.left = n.right = null
            n.right = lsubtree
            rmost = lsubtree
            while rmost != null:
                rmost = rmost.right
            rmost.right = rsubtree
        n = n.right
[Hat tip to LeCo]

No comments:

Post a Comment