Discription:
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
Solution:
我的解法:
void flatten(TreeNode* root) {
if (!root) return;
stack<TreeNode*> stack;
stack.push(root);
TreeNode* cur = new TreeNode(-1);
cur->right = root;
root = cur;
while (!stack.empty()){
TreeNode *temp = stack.top();
cur->right = temp;
cur->left = NULL;
cur = cur->right;
stack.pop();
if (temp->right)
stack.push(temp->right);
if (temp->left)
stack.push(temp->left);
}
root = root->right;
}
Leetcode上参考解法:
void flatten(TreeNode* root) {
if (!root) return;
stack<TreeNode*> stack;
stack.push(root);
while (!stack.empty()){
TreeNode *temp = stack.top();
stack.pop();
if (temp->right)
stack.push(temp->right);
if (temp->left)
stack.push(temp->left);
if (!stack.empty())
temp->right = stack.top();
temp->left = NULL;
}
}
void flatten(TreeNode* root) {
if (root == NULL) return;
TreeNode *left = root->left;
TreeNode *right = root->right;
root->left = NULL;
flatten(left);
flatten(right);
root->right = left;
TreeNode *cur = root;
while (cur->right != NULL) cur = cur->right;
cur->right = right;
}
void flatten(TreeNode *root) {
TreeNode *now = root;
while (now){
if (now->left){
TreeNode* pre = now->left;
while (pre->right)
pre = pre->right;
pre->right = now->right;
now->right = now->left;
now->left = NULL;
}
now = now->right;
}
}
GitHub-LeetCode:
https://github.com/wenwu313/LeetCode