问题描述:
/**
* 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
*/
把一个二叉树flatten 成一个像链表一样的树,如上图所示。
可以看出,结果树就是二叉树前序遍历的结果顺序。
所以,可以先把二叉树前序遍历一下,把遍历的结果存储到队列queue当中,再构建新的结果二叉树即可。
代码如下:
public void flatten(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<TreeNode>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
stack.push(root);
queue.add(root);
while (!stack.isEmpty()) {
TreeNode top = stack.peek();
if (top.left != null) {
queue.add(top.left);
stack.push(top.left);
top.left = null;
} else if (top.right != null) {
queue.add(top.right);
stack.push(top.right);
top.right = null;
} else { //top.left == null && top.right == null
stack.pop();
}
}
TreeNode node = queue.poll();
while (!queue.isEmpty()) {
node.right = queue.poll();
node = node.right;
}
}
上面这种方法借用了队列queue和栈stack。下面这种方法也很巧妙:
public void flatten(TreeNode root) {
if (root == null) return;
if (root.left != null) {
TreeNode rightMost = findRightMost(root.left);
TreeNode rightChild = root.right;
root.right = root.left;
root.left = null;
rightMost.right = rightChild;
}
flatten(root.right);
}
private TreeNode findRightMost(TreeNode root) {
if (root == null || root.right == null) return root;
return findRightMost(root.right);
}