LeetCode222 Count Complete Tree Nodes

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

Note:

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.

Example:

Input: 
    1
   / \
  2   3
 / \  /
4  5 6

Output: 6

思路:

我们使用分层遍历的思想完成该题,虽然理论上可以不完全遍历所有的节点,但是实际上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) {
        if(root == nullptr) return 0;
		list<TreeNode *> s;
		s.push_back(root);
		int count(0);
		while (!s.empty()) {
			TreeNode *top = s.front();
			s.pop_front();
			if (top->left) s.push_back(top->left);
			if (top->right) s.push_back(top->right);
			count++;
		}
		return count;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/89451053