LeetCode（114）： 二叉树展开为链表

Medium！

```    1
/ \
2   5
/ \   \
3   4   6```

```1
\
2
\
3
\
4
\
5
\
6```

C++解法一：

``` 1 // Recursion
2 class Solution {
3 public:
4     void flatten(TreeNode *root) {
5         if (!root) return;
6         if (root->left) flatten(root->left);
7         if (root->right) flatten(root->right);
8         TreeNode *tmp = root->right;
9         root->right = root->left;
10         root->left = NULL;
11         while (root->right) root = root->right;
12         root->right = tmp;
13     }
14 };```

```     1
/ \
2   5
/ \   \
3   4   6

1
/ \
2   5
\   \
3   6
\
4

1
\
2
\
3
\
4
\
5
\
6```

C++解法二：

``` 1 // Non-recursion
2 class Solution {
3 public:
4     void flatten(TreeNode *root) {
5         TreeNode *cur = root;
6         while (cur) {
7             if (cur->left) {
8                 TreeNode *p = cur->left;
9                 while (p->right) p = p->right;
10                 p->right = cur->right;
11                 cur->right = cur->left;
12                 cur->left = NULL;
13             }
14             cur = cur->right;
15         }
16     }
17 };```

```     1
/ \
2   5
/ \   \
3   4   6

1
\
2
/ \
3   4
\
5
\
6

1
\
2
\
3
\
4
\
5
\
6```

C++解法三：

``` 1 class Solution {
2 public:
3     void flatten(TreeNode* root) {
4         if (!root) return;
5         stack<TreeNode*> s;
6         s.push(root);
7         while (!s.empty()) {
8             TreeNode *t = s.top(); s.pop();
9             if (t->left) {
10                 TreeNode *r = t->left;
11                 while (r->right) r = r->right;
12                 r->right = t->right;
13                 t->right = t->left;
14                 t->left = NULL;
15             }
16             if (t->right) s.push(t->right);
17         }
18     }
19 };```

原文作者：Ariel_一只猫的旅行
原文地址: https://www.cnblogs.com/ariel-dreamland/p/9162548.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。