Binary Tree, recursive non-recursive traversal algorithm (full)

Source: Internet
Author: User

Binary Tree, recursive non-recursive traversal algorithm (full)

Contains all non-recursive and recursive algorithms:

# Include
 
  
# Include
  
   
# Include
   
    
Using namespace std; // Binary Tree node description typedef struct BiTNode {char data; struct BiTNode * lchild, * rchild; // left and right children} BiTNode, * BiTree; // traverse and create a binary tree in the First Order // BiTree * CreateBiTree () // return node pointer type // void CreateBiTree (BiTree & root) // reference type parameter void CreateBiTree (BiTNode ** root) // second-level pointer as function parameter {char ch; // scanf ("\ n % c ", & ch); // cin> ch; if (ch = '#') * root = NULL; else {* root = (BiTNode *) malloc (sizeof (BiTNode); (* root) -> Data = ch; printf ("Enter % c's left child:", ch); CreateBiTree (& (* root)-> lchild )); printf ("Enter the right child of % c:", ch); CreateBiTree (& (* root)-> rchild ));}} // void PreOrder (BiTNode * root) {if (root = NULL) return; printf ("% c", root-> data ); // output data PreOrder (root-> lchild); // recursive call, PreOrder traversal of the Left subtree PreOrder (root-> rchild); // recursive call, forward traversal right subtree} // The algorithm program void InOrder (BiTNode * root) {if (root = NULL) return; InOrder (root-> lchi Ld); // recursive call, traversing the left subtree printf ("% c", root-> data) in the forward order; // output data InOrder (root-> rchild ); // recursive call, right subtree traversal} // void PostOrder (BiTNode * root) {if (root = NULL) return; postOrder (root-> lchild); // recursive call, traversing the left subtree PostOrder (root-> rchild) in the forward order; // recursive call, traverse the right subtree printf ("% c", root-> data) in a forward order; // output data}/* Non-recursive forward traversal of a binary tree. The thought of forward traversal is as follows: let the root node go to the stack first. As long as the stack is not empty, the pop-up operation can be performed. Each time a node pops up, remember to add its left and right nodes to the stack, and remember the right subtree advanced stack, this ensures that the right subtree is always under the left subtree in the stack. */Void PreOrder_Nonrecursive2 (BiTree T) // non-recursive {if (! T) return; stack
    
     
S; s. push (T );//
     <首先将根节点压入while(!s.empty()) { bitree temp="s.top();" cout<
      
Data <"; s. pop ();//
      <输出最上方节点,同时弹出if(temp->
        Rchild) s. push (temp-> rchild );//
       <压入右节点 if(temp->
         Lchild) s. push (temp-> lchild );//
        <压入左节点} } void preorder_nonrecursive(bitree t) 先序遍历的非递归 { if(!t) return ; stack
          S; while (T) // All nodes on the left subtree are pushed to the stack {s. push (T); cout <
         
           Data <"; T = T-> lchild;} while (! S. empty () {BiTree temp = s. top ()-> rchild; // obtain the right subtree s of the top element of the stack. pop (); // The while (temp) element on the top of the stack pops up. // If the element on the top of the stack has the right subtree, the right subtree is traversed to the bottom {s. push (temp); cout <
          
            Data <"";//
           <前序遍历,在压入节点的时候就需要输出,表示根节点temp = temp->
             Lchild ;}} void InOrderTraverse (BiTree T) // non-recursive {if (! T) return; stack
            
              S; BiTree curr = T-> lchild; // <point to the current node S. push (T );//
             <先将根节点压入while(curr || !s.empty()) { while(curr) <一直找到对应的左节点最深处{ s.push(curr); curr="curr-">
               Lchild;} curr = S. top ();//
              <弹出栈顶,对应左孩子s.pop(); cout<
                Data <"";//
               <中序遍历,在压入节点之后,输出左孩子 curr="curr-">
                 Rchild ;//
                <调用右孩子,继续操作} } void postorder_nonrecursive(bitree t) 后序遍历的非递归 { stack
                  S; BiTree curr = T; // point to the current node BiTree previsited = NULL; // point to the previous accessed node while (curr |! S. empty () // end when stack is empty {while (curr) // keep walking left until it is empty {S. push (curr); curr = curr-> lchild;} curr = S. top (); // if the right child of the current node is empty or has been accessed, then access the current node if (curr-> rchild = NULL | curr-> rchild = previsited) {cout <
                 
                   Data <"; previsited = curr; S. pop (); curr = NULL;} else curr = curr-> rchild; // otherwise access the right child} void PostOrder_Nonrecursive2 (BiTree T) // non-recursive double stack method for post-sequential traversal {stack
                  
                    S1, s2; BiTree curr; // point to the current node s1.push (T); while (! S1.empty () // end when stack is empty {curr = s1.top (); s1.pop (); s2.push (curr); if (curr-> lchild) s1.push (curr-> lchild); if (curr-> rchild) s1.push (curr-> rchild);} while (! S2.empty () {printf ("% c", s2.top ()-> data); s2.pop () ;}} int visit (BiTree T) {if (T) {printf ("% c", T-> data); return 1;} else return 0;} void LeverTraverse (BiTree T) // method 1. Non-recursive layered traversal of Binary Tree {queue
                   
                     Q; BiTree p; p = T; if (visit (p) = 1) Q. push (p); while (! Q. empty () {p = Q. front (); Q. pop (); if (visit (p-> lchild) = 1) Q. push (p-> lchild); if (visit (p-> rchild) = 1) Q. push (p-> rchild) ;}} void LevelOrder (BiTree BT) // method 2. Non-recursive layered traversal of a binary tree {BiTNode * queue [10]; // define a queue with ten spaces if (BT = NULL) return; int front, rear; front = rear = 0; queue [rear ++] = BT; while (front! = Rear) // {cout <
                    
                      Data <""; // output the traversal result if (queue [front]-> lchild! = NULL) // pointer the left child of the first node of the queue to the queue {queue [rear] = queue [front]-> lchild; rear ++; // move the team's tail pointer one by one.} if (queue [front]-> rchild! = NULL) {queue [rear] = queue [front]-> rchild; // pointer the right child of the first node to the queue rear ++; // move the pointer at the end of the Team One by one} front ++; // move the pointer at the end of the Team One by one} int depth (BiTNode * T) // The depth of the tree {if (! T) return 0; int d1, d2; d1 = depth (T-> lchild); d2 = depth (T-> rchild); return (d1> d2? D1: d2) + 1; // return (depth (T-> lchild)> depth (T-> rchild )? Depth (T-> lchild): depth (T-> rchild) + 1;} int CountNode (BiTNode * T) {if (T = NULL) return 0; return 1 + CountNode (T-> lchild) + CountNode (T-> rchild);} int main (void) {BiTNode * root = NULL; // define a root node int flag = 1, k; printf ("this program implements the basic operations of Binary Trees. \ N "); printf (" can be used to establish Binary Trees, such as recursive first-order, middle-order, and post-order traversal, non-recursive first-order, middle-order traversal, and non-recursive sequence traversal. \ N "); printf (" Create a binary tree and enter the root node of the Binary Tree: "); CreateBiTree (& root); if (root) {printf ("the result of recursive first-order traversal of a binary tree is:"); PreOrder (root); printf ("\ n"); printf ("the result of recursive middle-order traversal of a binary tree is: "); InOrder (root); printf (" \ n "); printf (" the result of recursive post-sequential binary tree traversal is: "); PostOrder (root ); printf ("\ n"); printf ("non-recursive first-order traversal of a binary tree:"); PreOrder_Nonrecursive (root); printf ("\ n "); printf ("non-recursive middle-order traversal of Binary Trees:"); InOrderTraverse (root); printf ("\ n"); printf ("non-recursive post-order traversal of Binary Trees:"); PostOrder_Nonrecu Rsive (root); printf ("\ n"); printf ("non-recursive sequence traversal Binary Tree:"); // LeverTraverse (root); LevelOrder (root ); printf ("\ n"); printf ("the depth of this binary tree is % d \ n", depth (root); printf ("the number of nodes of this binary tree is: % d \ n ", CountNode (root); printf (" the program ends. Press any key to exit! \ N ");} system (" pause "); return 0 ;}
                    
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
 


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.