[leetcode] 114. Expand binary tree into linked list

Time:2020-3-28

subject

Given a binary tree, expand it into a linked list in place.

For example, given a binary tree

    1
   / \
  2   5
 / \   \
3   4   6

Expand it to:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

Title Solution

Kwai Chung is a classic topic. At the beginning, I thought the recursive solution was not good, but one thing I need to pay attention to when I recurse is that I need to recurse the right subtree first, and then record the chain header after the expansion of the right subtree. Then recursively solve the left subtree, and transfer the last chain of the left subtree to the chain header of the right subtree. Based on this, we use a pre pointer to record the head node of the right subtree.

class Solution {
    private TreeNode prev = null;

    public void flatten(TreeNode root) {
        if (root == null)
        return;
        flatten(root.right);
        flatten(root.left);
        root.right = prev;
        root.left = null;
        prev = root;
    }
}

It’s better to use stack instead of recursion.

class Solution {
    public void flatten(TreeNode root) {
        if (root == null) return;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode current = stack.pop();
            if (current.right != null) stack.push(current.right);
            if (current.left != null) stack.push(current.left);
            if (!stack.isEmpty()) current.right = stack.peek();
            current.left = null;
        }
    }
}

[leetcode] 114. Expand binary tree into linked list
QQ group discussion of code for manual tearing in case of problems: 805423079