Export copy_binary_tree (pbinary_tree_node BT) {// first traverse and output all node values of a tree 1, 2, 3 stacks <pbinary_tree_node> stack_left, stack_right; pbinary_tree_node newbt; If (BT! = NULL) {// new rootnewbt = new binary_tree_node; newbt-> DATA = Bt-> data; // travel Bt and travel newbt at the same timestack_left.push (BT ); stack_right.push (newbt); While (! Revoke () {pbinary_tree_node pleft = stack_left.top (); pbinary_tree_node pright = stack_right.top (); stack_left.pop (); stack_right.pop (); If! = 0) {stack_left.push (pleft-> rchild); pright-> rchild = new binary_tree_node; pright-> rchild-> DATA = pleft-> rchild-> data; stack_right.push (pright-> rchild);} If (pleft-> lchild! = 0) {stack_left.push (pleft-> lchild); pright-> lchild = new binary_tree_node; pright-> lchild-> DATA = pleft-> lchild-> data; stack_right.push (pright-> lchild) ;}} return newbt ;}
This algorithm uses two stacks. One stack is used to traverse the original binary tree. The other stack creates a new binary tree and synchronizes data with the first stack to save the history.