-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlattenBinaryTreeToLinkedList.cpp
More file actions
62 lines (59 loc) · 1.62 KB
/
FlattenBinaryTreeToLinkedList.cpp
File metadata and controls
62 lines (59 loc) · 1.62 KB
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
54
55
56
57
58
59
60
61
62
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/***
* 将先序遍历的结果组成一单链表,即为所求
* 先序遍历,递归实现
* 由于单链表由右孩子组成,原来的左孩子要覆盖右孩子,所以要保存右孩子
* 由于左子树处理完了,右子树要跟在左子树转换的链表后面next
* 所以得知道左子树的最后一个节点(上一个处理的节点)
***/
class Solution {
public:
void flatten(TreeNode *root) {
TreeNode *last = NULL;
preorderTravel(root, last);
}
private:
// caution, last node must be returned!!!
void preorderTravel(TreeNode *root, TreeNode *&last)
{
if (NULL == root)
return;
TreeNode *rchild = root->right; // right child will be replaced by lchild
if (last) // add cur node(root) to linked list
last->right = root;
last = root;
preorderTravel(root->left, last);
root->left = NULL; // update left child
preorderTravel(rchild, last);
return;
}
};
// 加一个虚头,可以不用判断上一个节点是否为空
class Solution {
public:
void flatten(TreeNode *root) {
TreeNode dummy(-1);
TreeNode *last = &dummy;
flattenRec(root, last);
}
private:
void flattenRec(TreeNode *root, TreeNode *&last) // preorder
{
if (!root)
return;
TreeNode *rchild = root->right;
last->right = root;
last = root;
flattenRec(root->left, last);
root->left = NULL; // break left subtree here!!!
flattenRec(rchild, last);
}
};