给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
重新构建一下二叉树
import java.util.LinkedList;
import java.util.List;
public class FlattenTest2 {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(5);
TreeNode t4 = new TreeNode(3);
TreeNode t5 = new TreeNode(4);
TreeNode t6 = new TreeNode(6);
t1.left = t2;
t1.right = t3;
t2.left = t4;
t2.right = t5;
t3.right = t6;
flatten(t1);
System.out.println("t1 = " + t1);
}
public static void flatten(TreeNode root) {
if (root == null) {
return;
}
LinkedList<TreeNode> list = new LinkedList<>();
dfs(root, list);
TreeNode head = list.removeFirst();
head.left = null;
while (list.size() > 0) {
TreeNode tempNode = list.removeFirst();
tempNode.left = null;
head.right = tempNode;
head = head.right;
}
}
private static void dfs(TreeNode root, List<TreeNode> list) {
if (root == null) {
return;
}
list.add(root);
if (root.left != null) {
dfs(root.left, list);
}
if (root.right != null) {
dfs(root.right, list);
}
}
}
本题的思路在以往的题解中已多次分析了,主要是重新构建二叉树