时间: 2020-11-25|59次围观|0 条评论

二叉树编程练习:

  • 求叶子节点数目
    void leafNum(BiTNode* root, int *num)
    {
        if (root == NULL)
        {
            //递归结束的条件,空树
            return;
        }
        //叶子节点
        if (root->lChild == NULL && root->rChild == NULL)
            (*num)++;
        //遍历左子树
        leafNum(root->lChild, num);
        //遍历右子树
        leafNum(root->rChild, num);
    
    }

     

  • 求二叉树的高度
    int treeDepth(BiTNode* root) 
    {
        if (root == NULL) return 0;
        //计算左子树的高度
        int left = treeDepth(root->lChild);
        //计算右子树的高度
        int right = treeDepth(root->rChild);
        //求出左右子树比较高的那个
        int max = left > right ? left : right;
    
        return max + 1;
    
    }

     

  • 拷贝树
    BiTNode* copyTree(BiTNode* root)
    {
        //空树
        if (root == NULL) return NULL;
        //拷贝左子树
        BiTNode* left = copyTree(root->lChild);
        //拷贝右子树
        BiTNode* right = copyTree(root->rChild);
        //创建一个新的节点
        BiTNode* pNew = new BiTNode;
        //初始化
        pNew->data = root->data;
        //指针域
        pNew->lChild = left;
        pNew->rChild = right;
        return pNew;
    }

     

 

转载于:https://www.cnblogs.com/Lan-ZC0803/p/9494331.html

原文链接:https://blog.csdn.net/weixin_30342827/article/details/98272490

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《二叉树知识总结(二)
   

还没有人抢沙发呢~