题目:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
题解:自己做的笨办法,用堆栈进行前序遍历。
C++版:
/**
* 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)
return;
if(!root->left && !root->right)
return;
stack<TreeNode*> unvisited;
unvisited.push(root);
while(unvisited.size()) {
TreeNode* current = unvisited.top();
unvisited.pop();
if(current->right) {
unvisited.push(current->right);
if(current->left) {
unvisited.push(current->left);
current->right = current->left;
current->left = NULL;
}
} else {
if(current->left) {
unvisited.push(current->left);
current->right = current->left;
current->left = NULL;
} else {
if(unvisited.size())
current->right = unvisited.top();
else
current->right = NULL;
}
}
}
}
};
网上学了一下空间复杂度O(1)算法,真正的in-place flattern。好像叫做Morris Algorithm for binary tree traversal。
Java版:
public class Solution {
public void flatten(TreeNode root) {
if(root == null)
return;
TreeNode current = root;
while(current != null) {
if(current.left != null) {
TreeNode next = current.left;
while(next.right != null)
next = next.right;
next.right = current.right;
current.right = current.left;
current.left = null;
}
current = current.right;
}
}
}
Python版:
class Solution:
# @param root, a tree node
# @return nothing, do it in place
def flatten(self, root):
if root == None:
return
current = root
while current != None:
if current.left != None:
next = current.left
while next.right != None:
next = next.right
next.right = current.right
current.right = current.left
current.left = None
current = current.right