Flatten Binary Tree to Linked List
Oct 14 '12
7105 / 21371
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
Hints:
» Solve this problem
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
按照道理应该1更快,但是实际貌似差不多。
1和2的区别,主要是在对flat( right,xx)的处理上。
/**
* 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) {
if (root == NULL) return;
TreeNode* tail;
flat(root, tail);
}
void flat(TreeNode* cur, TreeNode* &tail) {
if (cur->left == NULL && cur->right == NULL) {
tail = cur;
return;
}
if (cur->left != NULL) {
TreeNode* lefttail;
flat(cur->left, lefttail);
lefttail->right = cur->right;
cur->right = cur->left;
cur->left = NULL;
if (lefttail->right == NULL)
tail = lefttail;
else {
flat(lefttail->right, tail);
}
}
else {
flat(cur->right, tail);
}
}
};
/**
* 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) {
if (root == NULL) return;
TreeNode* tail;
flat(root, tail);
}
void flat(TreeNode* cur, TreeNode* &tail) {
if (cur->left == NULL && cur->right == NULL) {
tail = cur;
return;
}
if (cur->left != NULL) {
TreeNode* lefttail;
flat(cur->left, lefttail);
lefttail->right = cur->right;
cur->right = cur->left;
cur->left = NULL;
}
flat(cur->right, tail);
}
};