222. 完全二叉树的节点个数
222. 完全二叉树的节点个数
题目链接:222. 完全二叉树的节点个数
思路:该题可以用递归的前序,中序,后序遍历均可。但它强调该树是完全二叉树,个人感觉他是想让我们用层次遍历来进行解决。
代码如下:
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:int countNodes(TreeNode* root) {int count=0;countleaves(root,count);return count;}//前序遍历void countleaves(TreeNode* root,int &count){if(root==nullptr)return;count++;countleaves(root->left,count);countleaves(root->right,count);}
};