Count Complete Tree Nodes

原创 2015年07月11日 00:01:53

/**
 * 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:
    void traverseLeft(TreeNode* root, int& h)
    {
        if(root == NULL)
        {
            return;
        }
        ++ h;
        traverseLeft(root -> left, h); 
        
    }
    void traverseRight(TreeNode* root, int& h)
    {
        if(root == NULL)
        {
            return;
        }
        ++ h;
        traverseRight(root -> right, h);
    }

    int countNodes(TreeNode* root) 
    {
        if(root == NULL)
        {
            return 0;
        }
        int h1 = 1;
        int h2 = 1;
        traverseLeft(root -> left, h1);
        traverseRight(root -> right, h2);
        if(h1 == h2)
        {
            return pow(2, h1) - 1;
        }
        //int h = max(h1, h2);

        return countNodes(root -> left) + countNodes(root -> right) + 1;

    }
};


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

相关文章推荐

leetcode - Count Complete Tree Nodes

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

leetCode(19):Count Complete Tree Nodes

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

Binary search (4) -- Find Right Interval,Count Complete Tree Nodes,Divide Two Integers

Find Right Interval,Count Complete Tree Nodes,Divide Two Integers

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...

LeetCode——Count Complete Tree Nodes

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left...

222. Count Complete Tree Nodes

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

Count Complete Tree Nodes -- leetcode

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

leetcode--Count Complete Tree Nodes

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

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

Given a complete binary tree, count the number of nodes.Definition of a complete binary tree from Wi...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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