zoukankan      html  css  js  c++  java
  • 二叉树的插入,递归遍历和深度节点数

    二叉树的插入,前序,中序,后序遍历,递归求深度和节点数

    View Code
    #include<stdlib.h>
    #include<stdio.h>
    
    struct tree_el {
       int val;
       struct tree_el * right, * left;
    };
    
    typedef struct tree_el node;
    
    void insert(node ** tree, node * item) {
       if(!(*tree))
        {
          *tree = item;
          return;
        }
       if(item->val<=(*tree)->val)
          insert(&(*tree)->left, item);
       else if(item->val>(*tree)->val)
          insert(&(*tree)->right, item);
    }
    
    void InOrd(node * tree)
    {
       if(tree->left)
            InOrd(tree->left);
       printf("%d ",tree->val);
       if(tree->right)
            InOrd(tree->right);
    }
    
    void PreOrd(node *tree)
    {
        printf("%d ",tree->val);
        if(tree->left)
            PreOrd(tree->left);
       if(tree->right)
            PreOrd(tree->right);
    }
    
    void PostOrd(node *tree)
    {
        if(tree->left)
            PostOrd(tree->left);
       if(tree->right)
            PostOrd(tree->right);
        printf("%d ",tree->val);
    }
    
    int TreeDepth(node* tree)
    {
          // the depth of a empty tree is 0
          if(!tree)
                return 0;
    
          // the depth of left sub-tree
          int nLeft = TreeDepth(tree->left);
          // the depth of right sub-tree
          int nRight = TreeDepth(tree->right);
    
          // depth is the binary tree
          return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
    }
    
    int BTreeNodeCount(node *tree)
    {
        if(tree == 0)
            return 0;
        else
        {
            int l = BTreeNodeCount(tree->left);
            int r = BTreeNodeCount(tree->right);
            return l + r + 1;
        }
    }
    
    int main() {
       node * curr, * root;
       int i;
       int data;
       int lenth;
    
       root = NULL;
       printf("请输入要插入的元素,按Ctrl + Z结束输入\n");
       while(scanf("%d",&data)!= EOF)
       {
           curr = (node *)malloc(sizeof(node));
          curr->left = curr->right = NULL;
          curr->val = data;
          insert(&root, curr);
       }
       printf("先序遍历 : ");
       PreOrd(root);
    
       printf("\n中序遍历 : ");
       InOrd(root);
    
       printf("\n后序遍历 : ");
        PostOrd(root);
    
        printf("\n树的深度为 : %d\n", TreeDepth(root));
    
        printf("树的节点数为:%d\n", BTreeNodeCount(root));
    
        return 0;
    }
  • 相关阅读:
    add repository(仓库) EntityState状态
    添加 Attribute(属性)和Attribute的用法
    分部视图 Partial View
    MVC架构+ef 添加、删除、查询用户。。。
    首次接触 ef
    了解ASP.NET MVC的基本架构
    C# SqlParameter SqlCommand
    mysql命令行导出导入,附加数据库
    py03_变量
    py02_操作系统
  • 原文地址:https://www.cnblogs.com/genslow/p/2465848.html
Copyright © 2011-2022 走看看