第十二周

来源:互联网 发布:mysql 定位慢查询 编辑:程序博客网 时间:2024/05/18 02:30
                               第十二周                             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;        }    }这道题目无论是通过直接递归遍历, 还是通过队列来存储所有的节点,都是会超时,所以还是需要直接计算树的深度来解决。通过比较树的深度以及右子树的深度可以判断出是左子树还是右子树是满的,进而地使用递归的方式来进行计算。这种方式每次只计算两条路径,虽然有的是重复计算,但省略了中间部分节点的计算,所以总体上用时更少。

结果截图

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