第十二周

                               第十二周

                             2017/11/27

Count Complete Tree Nodes—-https://leetcode.com/problems/count-complete-tree-nodes/description/

问题描述:

Given a complete binary tree, count the number of nodes.

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

题目的意思就是计算出完全二叉树的节点数。

我自己的代码:

int countNodes(TreeNode* root) {
        if (root == NULL) return 0;

        int depth = 1;
        TreeNode* temp = root;

        /*计算树的深度*/
        while (temp->left != NULL) {
            depth++;
            temp = temp->left;
        }

        /*用来计算总的节点数*/
        return Compute(root, 1, depth);
    }

    /*root是树或者子树的根节点,current是当前的深度,target是目标的
    深度*/
    int Compute(TreeNode *root, int current, int target) {
        if (current == target) return 1;

        int count = 0;
        int right_depth = 0; // 记录右子树的深度
        TreeNode* temp = root->right;

        /*计算右子树的深度*/
        while (temp!= NULL) {
            right_depth++;
            temp = temp->left;
        }

        /*如果右子树的深度只比树的深度少1,那么左子树是满的,只需递归
        地计算右子树的总节点,左子树可以通过2 ^ (target - 1) - 1
        计算得到,加上根节点,就得到下面的式子;如果右子树的深度只比
        树的深度少2,那么右子树是满的,而左子树是不满的,那么只需递归
        地计算左子树的总节点,右子树可以通过2 ^ (target - 1) - 1
        计算得到,同理加上根节点。*/
        if (right_depth == target - 1) {
            count = pow(2, target - 1) + Compute(root->right, current, target - 1);
            return count;
        } else {
            count = pow(2, target - 2) + Compute(root->left, current, target - 1);
            return count;
        }
    }

这道题目无论是通过直接递归遍历, 还是通过队列来存储所有的节点,都是会超
时,所以还是需要直接计算树的深度来解决。通过比较树的深度以及右子树的深
度可以判断出是左子树还是右子树是满的,进而地使用递归的方式来进行计算。
这种方式每次只计算两条路径,虽然有的是重复计算,但省略了中间部分节点的
计算,所以总体上用时更少。

结果截图

我试过了几种方法,只有这种通过测试,其他都超时。但从截图的结果看到,时间效率也只是排在中间上一点点,所以应该会有更好的算法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值