10.6 Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example,Given

         1
        / \
       2   5
      / \   \
     3   4   6
The flattened tree should look like:

   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6
Hints:

If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

    private Node lastNode = null;
    public void flatten2(Node root) {
        if (root == null)return;

        if (lastNode != null) {
            lastNode.left = null;
            lastNode.right = root;
        }
        lastNode = root;
        Node right = root.right;

        flatten2(root.left);
        flatten2(right);
    }

Second Method

public void flatten(Node root) {
        if (root == null)
            return;
        Node l = root.left;
        Node r = root.right;

        root.left = null;
        root.right = null;

        flatten(l);
        flatten(r);

        if (l != null)
            root.right = l;
        Node c = root;
        while (c.right != null)
            c = c.right;
        c.right = r;
    }

Third Method - Non Recursive

https://siddontang.gitbooks.io/leetcode-solution/content/tree/flatten_binary_tree_to_linked_list.html

results matching ""

    No results matching ""