|
1 | 1 | /*
|
2 |
| - Author: Annie Kim, [email protected] |
| 2 | + |
3 | 3 | Date: Apr 28, 2013
|
4 |
| - Update: Sep 29, 2013 |
| 4 | + Update: Oct 7, 2014 |
5 | 5 | Problem: Flatten Binary Tree to Linked List
|
6 | 6 | Difficulty: Medium
|
7 | 7 | Source: http://leetcode.com/onlinejudge#question_114
|
|
27 | 27 | \
|
28 | 28 | 6
|
29 | 29 | Hints:
|
30 |
| - If you notice carefully in the flattened tree, each node's right child points to the next node |
| 30 | + If you notice carefully in the flattened tree, each node's right child points to the next node |
31 | 31 | of a pre-order traversal.
|
32 | 32 |
|
33 | 33 | Solution: Recursion. Return the last element of the flattened sub-tree.
|
|
45 | 45 | class Solution {
|
46 | 46 | public:
|
47 | 47 | void flatten(TreeNode *root) {
|
| 48 | + flatten_3(root); |
| 49 | + } |
| 50 | + |
| 51 | + void flatten_1(TreeNode *root) { |
| 52 | + if (root == NULL) return; |
| 53 | + flatten_1(root->left); |
| 54 | + flatten_2(root->right); |
| 55 | + if (root->left == NULL) return; |
| 56 | + TreeNode *p = root->left; |
| 57 | + while (p->right) p = p->right; |
| 58 | + p->right = root->right; |
| 59 | + root->right = root->left; |
| 60 | + root->left = NULL; |
| 61 | + } |
| 62 | + |
| 63 | + TreeNode * dfs (TreeNode * root, TreeNode * tail){ |
| 64 | + if(root == NULL) return tail; |
| 65 | + root->right = dfs(root->left,dfs(root->right,tail)); |
| 66 | + root->left = NULL; |
| 67 | + return root; |
| 68 | + } |
| 69 | + void flatten_2(TreeNode *root) { |
| 70 | + if(root == NULL) return; |
| 71 | + dfs(root, NULL); |
| 72 | + } |
| 73 | + void flatten_3(TreeNode *root) { |
| 74 | + if(root==nullptr) return; |
| 75 | + stack<TreeNode*> s; |
| 76 | + s.push(root); |
| 77 | + while(!s.empty()){ |
| 78 | + auto p=s.top(); |
| 79 | + s.pop(); |
| 80 | + if(p->right) s.push(p->right); |
| 81 | + if(p->left) s.push(p->left); |
| 82 | + p->left = nullptr; |
| 83 | + if(!s.empty()){ |
| 84 | + p->right=s.top(); |
| 85 | + }else p->right = nullptr; |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + void flatten_4(TreeNode *root) { |
48 | 90 | TreeNode *end = NULL;
|
49 | 91 | flattenRe(root, end);
|
50 | 92 | }
|
51 |
| - |
| 93 | + |
52 | 94 | void flattenRe(TreeNode *node, TreeNode *&end) {
|
53 | 95 | if (!node) return;
|
54 | 96 | TreeNode *lend = NULL, *rend = NULL;
|
|
0 commit comments