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
刚开始想偷懒想把几个条件混着写,但是写了半天没写出来。后来把4种分开写,很快就完成通过了。注意不是由树变链。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void flatten(TreeNode *root) { flat(root); } TreeNode * flat(TreeNode *root) { TreeNode *tail = root; TreeNode * l = root; TreeNode * r = root; if(root == NULL)return NULL; if(root->left == NULL && root->right == NULL)return root; if(root->left != NULL && root->right == NULL) { l= flat(root->left); root->right = root->left; root->left = NULL; return l; } else if(root->right!= NULL&&root->left == NULL) { r = flat(root->right); return r; } else { r = flat(root->right); l= flat(root->left); l->right = root->right; root->right= root->left; root->left =NULL; return r; } } };