您的位置:首页 > 其它

114. Flatten Binary Tree to Linked List

2016-04-18 02:25 447 查看
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 1

private TreeNode prev = null;

public void flatten(TreeNode root) {
if (root == null)
return;
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;
}

Solution 2

//straight forward
public void flatten2(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;
}

Solution 3 DFS stack

//DFS Use a stack
public void flatten3(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.isEmpty()){
TreeNode curr = stack.pop();
if (curr.right!=null)
stack.push(curr.right);
if (curr.left!=null)
stack.push(curr.left);
if (!stack.isEmpty())
curr.right = stack.peek();
curr.left = null; // dont forget this!!
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: