leetcode #222 Count Complete Tree Nodes

原创 2015年07月07日 20:43:05

       题目是要计算完全二叉树的节点数。首先看到题目很自然地想用递归的方法去做,但是写完后发现运行超时,递归的时间复杂度为O(n)。

       接下来,基于完全二叉树的特点,可以应用一种更快速的方法,每次比较前节点的最左子节点和最右子节点的深度,如果深度相同,那么以该节点为根节点的子树节点数为

2^h-1。如果不同就继续以该方式递归的计算左右子树的节点数,并加上当前节点,表达式写作 countNodes(root->left)+countNodes(root->right)+1。该方法的最好情况下复杂度为O(logn),即O(h),复杂度介于O(logn)与O(n)之间,速度有所提升。

/**
 * 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 lcount = 0, rcount = 0;
        TreeNode* left = root, *right = root;
        if (!root)
            return 0;
        
        while (left) {
            lcount++;
            left = left->left;
        }
        while (right) {
            rcount++;
            right = right->right;
        }
        
        if (lcount == rcount)
            return (2<<(lcount-1))-1;
        else
            return countNodes(root->left)+countNodes(root->right)+1;
    }
    
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode_c++:树: Count Complete Tree Nodes(222 )

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

leetcode——Count Complete Tree Nodes

题目Count Complete Tree Nodes Given a complete binary tree, count the number of nodes.In a complete b...

(未完成!)Leetcode 222. Count Complete Tree Nodes

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

leetcode222---Count Complete Tree Nodes(求完全二叉树节点数)

问题描述:Given a complete binary tree, count the number of nodes.In a complete binary tree every level, ...

Count Complete Tree Nodes - LeetCode 222

题目描述: Given a complete binary tree, count the number of nodes. Definition of a complete binary t...

leetcode 222:Count Complete Tree Nodes

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

LeetCode 222. Count Complete Tree Nodes 题解——Java

题目链接:https://leetcode.com/problems/count-complete-tree-nodes/#/description 题目要求:计算完全二叉树的节点个数 思...

leetcode -- 222. Count Complete Tree Nodes【子问题划分】

题目 Given a complete binary tree, count the number of nodes. Definition of a complete binary tree fr...

[LeetCode222]Count Complete Tree Nodes

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

222. Count Complete Tree Nodes

//超时 class Solution { public: int countNodes(TreeNode* root) { if(!root) return 0; ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)