Count Complete Tree Nodes

题目来源
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.
给一个完整二叉树,求节点数目。
最直观的方法就是遍历,例如用深度优先遍历,代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int countNodes(TreeNode* root) {
        int l = 0;
        TreeNode *cur = root;
        int res = 0;
        if (root)
            dfs(root, res);
        return res;
    }
    
    void dfs(TreeNode* node, int &count)
    {
        if (node)
            count++;
        else 
            return;
        dfs(node->left, count);
        dfs(node->right, count);
    }
};

没错,又TLE了。想想除了最后一层,其他的都可以直接算出来,因为是满的,但是最后一层的节点数目应该怎么算呢?
没有什么特别直观的想法。
看了下答案,主要是这么一个类似的剪枝过程,就是假如是满二叉树就直接算,不是的话就看左右子树的情况,递归。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int countNodes(TreeNode* root) {
        TreeNode *l = root, *r = root;
        int hl = 0, hr = 0;
        while (l) {
            hl++;
            l = l->left;
        }
        while (r) {
            hr++;
            r = r->right;
        }
        return (hl == hr) ? (pow(2, hl) - 1) : (1 + countNodes(root->left) + countNodes(root->right));
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容