Algorithm/java/三叉链表parent链深拷贝/BiTree.java

62 lines
1.8 KiB
Java
Raw Normal View History

2022-03-03 18:03:39 +08:00
package site.licsber.bitree;
public class BiTree<T> {
public static <T> Node<T> deepCopy(Node<T> srcRoot) {
if (srcRoot == null) {
return null;
}
Node<T> p = srcRoot;
Node<T> res = new Node<>(p.data);
Node<T> q = res;
while (p != null) {
while (p.left != null && q.left == null) {
p = p.left;
q = new Node<>(p.data, q);
System.out.println(q);
q.parent.left = q;
}
if (p.right != null && q.right == null) {
p = p.right;
q = new Node<>(p.data, q);
System.out.println(q);
q.parent.right = q;
} else {
while (p.parent != null && p.parent.right == p) {
p = p.parent;
q = q.parent;
}
p = p.parent;
q = q.parent;
}
}
return res;
}
public static <T> void walk(Node<T> node) {
if (node != null) {
System.out.print(node);
walk(node.left);
walk(node.right);
}
}
public static void main(String[] args) {
Node<String> testRoot = new Node<>("A");
testRoot.left = new Node<>("B", testRoot);
testRoot.right = new Node<>("C", testRoot);
testRoot.left.left = new Node<>("D", testRoot.left);
testRoot.left.left.right = new Node<>("G", testRoot.left.left);
testRoot.right.left = new Node<>("E", testRoot.right);
testRoot.right.right = new Node<>("F", testRoot.right);
testRoot.right.right.left = new Node<>("H", testRoot.right.right);
walk(testRoot);
System.out.println();
Node<String> copyRoot = deepCopy(testRoot);
walk(copyRoot);
}
}