Copying a binary tree (non-Recursive Implementation)

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.