数据结构与算法-第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

转载于:https://www.cnblogs.com/shamgod/p/5295544.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值