我正在尝试使用预订序遍历来复制二叉树,但我被卡住了。 由于我没有将任何值放入新树中,因此它们显然无法正确复制...
public class Node{
int key;
String name;
Node leftChild;
Node rightChild;
Node(int key, String name){
this.key = key;
this.name = name;
}
public class BinaryTree{
public Node root;
public void copyTree(Node focusNode){
if(focusNode != null){
Node copyNode = new Node(focusNode.key, focusNode.name);
//System.out.println(copyNode);
copyTree(focusNode.leftChild);
copyTree(focusNode.rightChild);
}
}
}
答案 0 :(得分:0)
这是一个解决方案。我为toString()
课程添加了Node
方法以供演示。
class Node {
int key;
String name;
Node leftChild;
Node rightChild;
Node(int key, String name) {
this.key = key;
this.name = name;
}
public String toString() {
return "[" + key + "," + name + "]";
}
}
BinaryTree
也略有修改:
class BinaryTree {
public Node root;
public BinaryTree copyTree(Node focusNode) {
BinaryTree bt = new BinaryTree();
bt.root = preOrderCopy(focusNode);
return bt;
}
public static void preOrderPrint(BinaryTree t) {
preOrderPrint(t.root);
}
public static void preOrderPrint(Node n) {
if (n == null) {
// base case
return;
}
System.out.println(n);
preOrderPrint(n.leftChild);
preOrderPrint(n.rightChild);
}
private Node preOrderCopy(Node focusNode) {
if (focusNode == null) {
// base case
return null;
}
Node copy = new Node(focusNode.key, focusNode.name);
copy.leftChild = preOrderCopy(focusNode.leftChild);
copy.rightChild = preOrderCopy(focusNode.rightChild);
return copy;
}
}
为了测试代码,我根据Wikipedia page for Tree Traversal上显示的内容创建了BinaryTree
。这是本例中使用的树的图片:
此示例的正确预订遍历为:F, B, A, D, C, E, G, I, H
。您可以使用以下代码来测试此实现:
public class NodeTest {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
Node a = new Node(1, "A");
Node b = new Node(2, "B");
Node c = new Node(3, "C");
Node d = new Node(4, "D");
Node e = new Node(5, "E");
Node f = new Node(6, "F");
Node g = new Node(7, "G");
Node h = new Node(8, "H");
Node i = new Node(9, "I");
f.leftChild = b;
b.leftChild = a;
b.rightChild = d;
d.leftChild = c;
d.rightChild = e;
f.rightChild = g;
g.rightChild = i;
i.leftChild = h;
bt.root = f;
System.out.println("Print full tree:");
BinaryTree.preOrderPrint(bt.copyTree(f));
System.out.println("Only print f's left sub-tree:");
BinaryTree.preOrderPrint(bt.copyTree(f.leftChild));
}
}
运行上面的代码会产生以下输出:
Print full tree:
[6,F]
[2,B]
[1,A]
[4,D]
[3,C]
[5,E]
[7,G]
[9,I]
[8,H]
Only print f's left sub-tree:
[2,B]
[1,A]
[4,D]
[3,C]
[5,E]
答案 1 :(得分:0)
从树a复制到树b。你可以使用像我这样的两种静态方法。我的想法来自添加Element方法和删除Element方法。它们很相似。
public static Node copyRec(Node a, Node b)//copy from b to a
{
if(b!=null)
{
a=new Node(b.data);
a.leftChild=copyRec(a.leftChild,b.leftChild);
a.rightChild=copyRec(a.rightChild,b.rightChild);
return a;
}
return null;
}
public static void copy(BST a, BST b)
{
a.root=copyRec(a.root,b.root);
}