Sword refers to offer interview questions 19-binary tree image, sword refers to offer

Source: Internet
Author: User

Sword refers to offer interview questions 19-binary tree image, sword refers to offer

Question:

Complete a function, input a binary tree, and the function outputs its image.



Basic Idea:


Each node in the tree is traversed in the previous order. If the node to be traversed has a subnode, it will exchange its two subnodes. After switching all the left and right subnodes of non-leaf nodes, the tree image is obtained.

# Include <iostream> # include <deque> using namespace std; // The Binary Tree node defines the typedef struct BiTreeNode {int data; // The left and right child pointer struct BiTreeNode * lchild; struct BiTreeNode * rchild;} BiTreeNode, * BiTree; // create a binary tree int CreateBiTree (BiTree & T) {int data; // enter the value of the node in the binary tree in the First Order (one character). '#' indicates the empty tree cin> data; if (data =-1) {T = NULL;} else {T = (BiTree) malloc (sizeof (BiTreeNode); T-> data = data; // generate the root node CreateBiTree (T-> lchild); // construct the left subtree CreateBiTr Ee (T-> rchild); // construct the right subtree} return 0;} void foo (BiTree T) {if (T = NULL) return; if (T-> lchild = NULL & T-> rchild = NULL) return; BiTree Tmp = T-> lchild; T-> lchild = T-> rchild; t-> rchild = Tmp; if (T-> lchild) foo (T-> lchild); if (T-> rchild) foo (T-> rchild );} // access function void Visit (BiTree T) {if (T-> data! =-1) cout <T-> data <";}// first traverse void PreOrder (BiTree T) {if (T! = NULL) {// access the root node Visit (T); // access the left subnode PreOrder (T-> lchild ); // access the right subnode PreOrder (T-> rchild) ;}} void main () {BiTree T; CreateBiTree (T); cout <"original binary tree :"; preOrder (T); cout <endl; foo (T); cout <"Image Binary Tree:"; PreOrder (T); cout <endl ;}


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.