Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
递归实现,处理一个节点的时候,用同样的方法处理它的左右子节点,将这个节点的左子节点连接到右子节点的位置,将原来的右子节点连接到左子节点处理后的最后一个节点的右子节点上。返回这个点处理后的最后一个元素。
1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 TreeNode * convert(TreeNode *root)
13 {
14 if (root == NULL)
15 return NULL;
16 TreeNode * leftNode = convert(root->left);
17 TreeNode * rightNode = convert(root->right);
18 TreeNode * lhead = root->left;
19 TreeNode * rhead = root->right;
20 root->right = NULL;
21 root->left = NULL;
22 if (lhead)
23 {
24 root->right = lhead;
25 leftNode->right = rhead;
26 }
27 else
28 root->right = rhead;
29 TreeNode *tail;
30 if (rightNode != NULL)
31 tail = rightNode;
32 else if (leftNode != NULL)
33 tail = leftNode;
34 else
35 tail = root;
36 return tail;
37 }
38
39 void flatten(TreeNode *root) {
40 // Start typing your C/C++ solution below
41 // DO NOT write int main() function
42 convert(root);
43 }
44 };