-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlatten Binary Tree to Linked List.cpp
53 lines (49 loc) · 1.37 KB
/
Flatten Binary Tree to Linked List.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Flatten a binary tree to a fake "linked list" in pre-order traversal.
Here we use the right pointer in TreeNode as the next pointer in ListNode.
Link: http://www.lintcode.com/en/problem/flatten-binary-tree-to-linked-list/
Example:
1 1
/ \ \
2 5 => 2
/ \ \ \
3 4 6 3
\
4
\...
Solution: use recursion to get flatten list order (root, left, right)
Source: https://github.com/kamyu104/LintCode/blob/master/C%2B%2B/flatten-binary-tree-to-linked-list.cpp
*/
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void flatten(TreeNode *root) {
// write your code here
TreeNode *list_head = nullptr;
flatterHelper(root, &list_head);
}
TreeNode *flatterHelper(TreeNode *root, TreeNode **list_head) {
if (root) {
flatterHelper(root->right, list_head);
flatterHelper(root->left, list_head);
root->right = *list_head;
root->left = nullptr;
*list_head = root;
}
}
};