标签:
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) { return count_nodes(root); } int count_nodes(TreeNode* root) { if (root == NULL) { return 0; } int cnt = 1; cnt += count_nodes(root->left) + count_nodes(root->right); return cnt; } };
当然TLE了
因为完全二叉树如果去掉最后最后一层,那么剩下的这H-1层组成的树就是一颗满二叉树,不用去数其中的节点,直接可以计算得出为(2^(H-1))-1个,所以只要求出最后一层的节点个数加上即可。
LeetCode Count Complete Tree Nodes
标签:
原文地址:http://www.cnblogs.com/lailailai/p/4558393.html