数据结构与算法-第12章二叉树和其他树-002克隆二叉树
例子中二叉树用链表示
1.后序遍历克隆和前序遍历克隆
1 package chapter12Tree; 2 3 //In writing the cloning codes, we assume that we are not to 4 //make clones of the elements in the nodes. Only the tree structure is to be cloned. 5 //In case the elements are also to be cloned, then we must replace all occurrences 6 //of element by code to first cast element into a CloneableObject, 7 //and then invoke the method clone on the reulting object. 8 public class BinaryTreeCloning 9 { 10 /** preorder cloning 11 * @return root of clone */ 12 public static BinaryTreeNode preOrderClone(BinaryTreeNode t) 13 { 14 if (t != null) 15 {// nonempty tree 16 // make a clone of the root 17 BinaryTreeNode ct = new BinaryTreeNode(t.element); 18 19 // now do the subtrees 20 ct.leftChild = preOrderClone(t.leftChild); // clone left subtree 21 ct.rightChild = preOrderClone(t.rightChild); // clone right subtree 22 return ct; 23 } 24 else 25 return null; 26 } 27 28 /** postorder cloning 29 * @return root of clone */ 30 public static BinaryTreeNode postOrderClone(BinaryTreeNode t) 31 { 32 if (t != null) 33 {// nonempty tree 34 // clone left subtree 35 BinaryTreeNode cLeft = postOrderClone(t.leftChild); 36 37 // clone right subtree 38 BinaryTreeNode cRight = postOrderClone(t.rightChild); 39 40 // clone root 41 return new BinaryTreeNode(t.element, cLeft, cRight); 42 } 43 else 44 return null; 45 } 46 } 47 48 class BinaryTreeNode { 49 int element; 50 BinaryTreeNode leftChild, rightChild; 51 52 // constructors 53 BinaryTreeNode() {} 54 55 BinaryTreeNode(int element) { 56 this.element = element; 57 this.rightChild = null; 58 this.leftChild = null; 59 } 60 BinaryTreeNode(int element, BinaryTreeNode rc, BinaryTreeNode lc) { 61 this.element = element; 62 this.rightChild = rc; 63 this.leftChild = lc; 64 } 65 }
The recursion stack space needed by both the preorder and postorder copy methods is O(h)
, where h
is the height of the binary tree being cloned
You can do anything you set your mind to, man!