LeetCode 114 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

click to show hints.

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

Diffculty
Medium

Similar Problems

Analysis

根据展开后形成的链表的顺序分析出是使用先序遍历,那么只要是数的遍历就有递归和非递归的两种方法来求解,这里我们也用两种方法来求解。

思路一:递归版本 是深度优先找到最左叶子节点,然后回到其父节点,把其父节点和右子节点断开,将原左子结点作为其父节点的右子节点连上,然后再把原右子节点连到新右子节点的右子节点上,然后再回到上一父节点做相同操作。

变换过程:

    1
   / \
  2   5
 / \   \
3   4   6

  1
 / \
2   5
 \   \
  3   6
   \    
    4

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

思路二:非递归 从根节点开始出发,先检测其左子结点是否存在,如存在则将根节点和其右子节点断开,将左子结点及其后面所有结构一起连到原右子节点的位置,把原右子节点连到原左子结点最后面的右子节点之后。

变换过程:

    1
   / \
  2   5
 / \   \
3   4   6

1
 \
  2
 / \
3   4
     \
      5
       \
        6

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6
Solutions
  1. Recursive
class Solution {
public:
    void flatten(TreeNode *root) {
        if (root == nullptr) return;
        if (root->left) flatten(root->left);
        if (root->right) flatten(root->right);
        TreeNode *tmp = root->right;
        root->right = root->left;
        root->left = nullptr;
        while (root->right) root = root->right;
        root->right = tmp;
    }
};
  1. Non-Recursive
class Solution {
public:
    void flatten(TreeNode *root) {
        TreeNode *cur = root;
        while (cur) {
            if (cur->left) {
                TreeNode *p = cur->left;
                while (p->right) p = p->right; // 找到左子节点最右的叶子结点,把原根节点的有节点连到这里
                p->right = cur->right;
                cur->right = cur->left;
                cur->left = nullptr;
            }
            cur = cur->right;
        }
    }
};
Reference

results matching ""

    No results matching ""