• 求二叉树结点个数和深度


    typedef struct Node{                        
        struct Node *lchild;                    
        char data;                
        struct Node *rchild;
    }BTNode;    
     //求二叉树中的节点个数 1)如果二叉树为空,节点个数为0  
    (2)如果二叉树不为空,二叉树节点个数 = 左子树节点个数 + 右子树节点个数 + 1
    
    int getNodeNum(BTNode* root) 
    {    
        if(root == NULL) {
            return 0;
         }else{
            return getNodeNum(root->lchild) + getNodeNum(root->rchild) + 1;
         }        
    } 
    //求二叉树中叶子节点的个数1)如果二叉树为空,返回0 
    (2)如果二叉树不为空且左右子树为空,返回1 
    (3)如果二叉树不为空,且左右子树不同时为空,返回左子树中叶子节点个数加上右子树中叶子节点个数 
    int getLeafNodeNum(BTNode* root)
    {
        if(root == NULL)
            return 0;
        if(root->lchild == NULL && root->rchild == NULL)
            return 1;
        int leftNum = getLeafNodeNum(root->lchild); //左子树中叶节点的个数
        int rightNum = getLeafNodeNum(root->rchild); //右子树中叶节点的个数
        return (leftNum +rightNum);
    }
    //求二叉树第k层的节点个数 1)如果二叉树为空或者k<1返回0 
    (2)如果二叉树不为空并且k==1,返回1 
    (3)如果二叉树不为空且k>1,返回左子树中k-1层的节点个数与右子树k-1层节点个数之和 
    
    int getNodeNumKthLevel(BTNode* root, int k)
    {
        if(root==NULL || k<1)
            return 0;
        if(k == 1)
            return 1;
        int leftNum = getNodeNumKthLevel(root->lchild, k-1); //左子树中k-1层的节点个数
        int rightNum = getNodeNumKthLevel(root->rchild, k-1); //右子树中k-1层的节点个数
        return (leftNum + rightNum);
    }
    //求二叉树的深度
    (1)如果二叉树为空,二叉树的深度为0 
    (2)如果二叉树不为空,二叉树的深度 = max(左子树深度, 右子树深度) + 1
    int
    depth(BTNode* root) { if(root==NULL){//头指针为空 return 0; } else { int m = depth(root->lchild ); int n = depth(root->rchild); return (m>n)?(m+1):(n+1);//1是加上顶点的深度 } }
    二叉树的最小深度:从根节点到最近叶子节点的最短路径上的节点数量。。
    int minDepth(BTNode *root) {
        if(root == NULL){
           return 0;
        }
        if(root->lchild == NULL&&root->rchild == NULL){
            return 1;
        }
        //若左子树为空,则返回右子树的深度,反之返回左子树的深度
        if(root->lchild == NULL){
            return minDepth(root->rchild) + 1;
        }else if(root->rchild == NULL){
            return  minDepth(root->lchild) + 1;
        }else{
            //如果都不为空,则返回左子树和右子树深度的最小值
            int leftDepth = minDepth(root->lchild) + 1;
            int rightDepth = minDepth(root->rchild) + 1;
            return leftDepth<rightDepth ? leftDepth:rightDepth;
        
        }
    
    }
  • 相关阅读:
    [POJ1743]Musical Theme
    ubuntu qq
    Separate code and data contexts: an architectural approach to virtual text sharing
    Python3发送post请求,自动记住cookie
    python 异步协程
    豆瓣爬虫
    pandas 使用
    房天下爬虫
    计算英文文章词频的两种方法
    LOW版统计词频
  • 原文地址:https://www.cnblogs.com/shijianchuzhenzhi/p/12390937.html
Copyright © 2020-2023  润新知