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

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

/**
* @param n current node
* @param pre previous node in pre-order traversal
*/
void flatten(TreeNode *n, TreeNode *&pre) { if (n == NULL) return; if (pre != NULL) { pre->right = n; } pre = n; TreeNode *rChild = n->right; //reserve right child in case it pointer to flatten node flatten(n->left, pre); n->left = NULL; //clear left node flatten(rChild, pre); } void flatten(TreeNode *root) { TreeNode *pre = NULL; flatten(root, pre); }
View Program Text


Test Status