leetcode15: flatten binary tree
Flatten Binary Tree to Linked ListOct 14 '12
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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
Queue<TreeNode> queue = new LinkedList<TreeNode>();
//preorder traversal.
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while(!stack.isEmpty() || node != null) {
if(node!=null) {
queue.add(node);
stack.push( node );
node = node.left;
} else {
node = stack.pop();
node = node.right;
}
}
while( !queue.isEmpty() ) {
node = queue.remove();
node.left = null;
node.right = queue.peek();
}
}
}uncomplete
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
flattenRec( root);
}
TreeNode* flattenRec( TreeNode *root) {
if(!root) return NULL;
TreeNode* tail = NULL;
if(root->left){
tail = flattenRec(root->left);
} else {
tail = root;
}
TreeNode * temp = root->right;
root->right = root->left;
if(temp) {
tail->right = temp;
tail = flattenRec(temp);
}
return tail;
}
};
浙公网安备 33010602011771号