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 ;}