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
非递归
public void flatten(TreeNode root) {
if(root == null) return;
if(root.right == null && root.left == null) return;
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
TreeNode tmp = root;
if(root.right != null) stack.push(root.right);
if(root.left != null) stack.push(root.left);
while(!stack.isEmpty()){
TreeNode cur = stack.pop();
tmp.right = cur;
tmp.left = null;
tmp = tmp.right;
if(cur.right != null) stack.push(cur.right);
if(cur.left != null) stack.push(cur.left);
}
}
递归
TreeNode pre;
public void flatten(TreeNode root) {
if(root == null) return;
flatten(root.right);
flatten(root.left);
root.right = pre;
root.left = null;
pre = root;
}