[Data structure] Establishment and basic operations of Binary Trees

Source: Internet
Author: User

Code:

# Include
 
  
# Include
  
   
# Include
   
    
Using namespace std; char ch; typedef struct BinNode {char data; struct BinNode * lchild, * rchild;} BinNode, * BinTree; // Binary Tree chain storage structure void CreateBinTree (BinTree & T) // create a binary tree in the first order {ch = cin. get (); if (ch = '') T = NULL; else if (ch = '\ n') return; else {T = (BinNode *) malloc (sizeof (BinNode); T-> data = ch; // This is the root node CreateBinTree (T-> lchild ); // create the left child CreateBinTree (T-> rchild); // create the right child} void PreOrder (BinTree T) // traverse the binary tree in the forward order {if (T! = NULL) {cout <
    
     
Data; PreOrder (T-> lchild); PreOrder (T-> rchild) ;}} void InOrder (BinTree T) // traverses a binary tree in the middle order {if (T! = NULL) {InOrder (T-> lchild); cout <
     
      
Data; InOrder (T-> rchild) ;}} void PostOrder (BinTree T) // post-order traversal of a binary tree {if (T! = NULL) {PostOrder (T-> lchild); PostOrder (T-> rchild); cout <
      
        Data ;}} int cnt = 0; int countNode (BinTree T) // calculate the number of nodes in the binary tree {if (T) {cnt ++; countNode (T-> lchild); countNode (T-> rchild);} return cnt;} int depthval = 0; int dl = 0; int dr = 0; int Depth (BinTree T) // calculate the height of the Binary Tree {if (! T) return 0; else {dl = Depth (T-> lchild); dr = Depth (T-> rchild); depthval = 1 + (dl> dr? Dl: dr); return depthval;} int main () {// freopen ("in.txt", "r", stdin); BinTree T; cout <"input the element values of each node of the binary tree in the FIFO order. If the leaf node is empty, it is expressed by space:" <
       
        


Run:

Note that at the time of input, there are two spaces behind G.

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.