Example of a binary tree with a chain representation
1. Post-order traversal clones and pre-sequence traversal clones
1 PackageChapter12tree;2 3 //in writing the cloning codes, we assume the.4 //Make clones of the elements in the nodes. Only the tree structure are to be cloned. 5 //in case the elements is also to being cloned, then we must replace all occurrences6 //of element by code to first cast element into a cloneableobject,7 //And then invoke the method, clone on the reulting object.8 Public classbinarytreecloning9 {Ten /**Preorder Cloning One * @returnroot of Clone*/ A Public StaticBinarytreenode Preorderclone (Binarytreenode t) - { - if(t! =NULL) the{//nonempty Tree - //Make a clone of the root -Binarytreenode ct =NewBinarytreenode (t.element); - + //Now do the subtrees -Ct.leftchild = Preorderclone (t.leftchild);//Clone left subtree +Ct.rightchild = Preorderclone (t.rightchild);//Clone right subtree A returnCT; at } - Else - return NULL; - } - - /**postorder Cloning in * @returnroot of Clone*/ - Public StaticBinarytreenode Postorderclone (Binarytreenode t) to { + if(t! =NULL) -{//nonempty Tree the //Clone left subtree *Binarytreenode cleft =Postorderclone (t.leftchild); $ Panax Notoginseng //Clone right subtree -Binarytreenode cright =Postorderclone (t.rightchild); the + //Clone Root A return NewBinarytreenode (t.element, cleft, cright); the } + Else - return NULL; $ } $ } - - classBinarytreenode { the intelement; - Binarytreenode leftchild, rightchild;Wuyi the //Constructors - Binarytreenode () {} Wu -Binarytreenode (intElement) { About This. Element =element; $ This. Rightchild =NULL; - This. Leftchild =NULL; - } -Binarytreenode (intelement, Binarytreenode RC, Binarytreenode LC) { A This. Element =element; + This. Rightchild =RC; the This. Leftchild =LC; - } $}
The recursion stack space needed by both the preorder and Postorder copy methods O(h) are, where is the h height of th e binary tree being cloned
Data structure and algorithms-12th two fork tree and other tree-002 Clone binary Tree