您的位置:首页 > Web前端 > Node.js

LeetCode-Count Complete Tree Nodes -解题报告

2015-06-29 22:15 671 查看
原题链接https://leetcode.com/problems/count-complete-tree-nodes/

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

计算完全二叉树的节点个数,开始写了个最普通的超时了,后来改进了一下 找到树的最深的深度(从1开始),然后 在数叶子的个数,然后计算2^n - 1 + 叶子个数。然而无情超时。

后来看了大牛的做法,忘记是谁的了。

大概就是从沿着当前节点的左子树得到左边的深度L,然后再沿着右子树得到右边的深度。

如果L==R,以为以该节点为根的树的节点数为 2^L - 1;

如果L!=R,递归调用 1 + countNodes(root->left) + countNodes(root->right)

/**
* 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) {
if (root == NULL)return 0;
int l = getleft(root);
int r = getright(root);
if (l == r)return (1 << l) - 1;
return 1 + countNodes(root->left) + countNodes(root->right);
}
int getleft(TreeNode* root)
{
if (root == NULL)return 0;
return 1 + getleft(root->left);
}
int getright(TreeNode* root)
{
if (root == NULL)return 0;
return 1 + getright(root->right);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode