跳转至

114. Flatten Binary Tree to Linked List

Leetcode Tree Depth-first Search

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

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

分析

把二叉树转换成链表,也就是用二叉树的右指针(TreeNode.right)表示链表的next指针(ListNode.next).根据链表的形态,进行的是先序遍历(144. Binary Tree Preorder Traversal)。那么改编一下先序遍历就可以得到所求的链表。

public void flatten(TreeNode root) {
    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    TreeNode prevNode = null;

    while (!stack.isEmpty()) {
        TreeNode cur = stack.pop();
        if (cur != null) {
            stack.push(cur.right);
            stack.push(cur.left);
            if (prevNode != null) {
                prevNode.right = cur;
            }
            cur.left = null;
            prevNode = cur;
        }
    }
    preNode.right = null;
}

下面用前序遍历的递归方法,这种方法比前面一种快一些(17ms->13ms),但是写的过程中比较容易出错。特别是需要注意要先保存root.left和root.right,因为在递归时会发生改变。

private TreeNode prevNode ;
public void flatten(TreeNode root) {
    if (root == null) return;
    if (prevNode != null) prevNode.right = root;
    TreeNode left = root.left, right = root.right;
    root.left = null;
    prevNode = root;
    flatten(left);
    flatten(right);
}

论坛上有一种非常完美的方案,使用后序遍历(145. Binary Tree Postorder Traversal)的递归方法,

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;
}