-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflatTree.cpp
More file actions
28 lines (28 loc) · 833 Bytes
/
flatTree.cpp
File metadata and controls
28 lines (28 loc) · 833 Bytes
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
pre = new TreeNode(0);
preorder(root);
}
void preorder(TreeNode* root){
if (!root) return;
TreeNode* left = root->left; //First you need to record the left children and the right children because in recursion they will be modified and missing
TreeNode* right = root->right;
pre->right = root;
pre->left = NULL;
pre = root; // In this manner the pre is working as a pointer of the flat linked tree leading all way down
preorder(left);
preorder(right);
}
private:
TreeNode* pre;
};