题目:
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
对整棵树一直向右子树方向遍历。当遍历的节点有右孩子时,就将其入栈。有左孩子时,将其更新为当前节点的右孩子,左孩子置空。当左孩子为空时而栈不空时,就弹出栈,作为右孩子。
代码如下:
public class FlattenBinaryTreetoLinkedList {
public static void main(String[] args) {
/**
* Given a binary tree, flatten it to a linked list in-place.
*
* For example, given the following tree:
*
* 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like:
*
* 1 \ 2 \ 3 \ 4 \ 5 \ 6
*/
TreeNode root = new TreeNode(1);
TreeNode tn2 = new TreeNode(2);
TreeNode tn3 = new TreeNode(3);
TreeNode tn4 = new TreeNode(4);
TreeNode tn5 = new TreeNode(5);
TreeNode tn6 = new TreeNode(6);
root.left = tn2;
root.right = tn5;
tn2.left = tn3;
tn2.right = tn4;
tn5.right = tn6;
flatten(root);
while (root != null) {
System.out.println(root.val);
if (root.left != null) {
System.out.println("Error");
break;
}
root = root.right;
}
}
public static void flatten(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode tn = root;
while (tn != null) {
if (tn.right != null) {
stack.push(tn.right);
}
if (tn.left != null) {
tn.right = tn.left;
tn.left = null;
} else {
if (!stack.isEmpty()) {
tn.right = stack.pop();
}
}
tn = tn.right;
}
}
}