Post

lc.222 完全二叉树的节点个数

lc.222 完全二叉树的节点个数

1)层序遍历法

可以按照普通二叉树的逻辑来求:
把层序遍历的模板稍稍修改一下,记录遍历的节点数量就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int countNodes(TreeNode* root) {

        if(!root){return 0;}
        
        queue<TreeNode*>que;
        que.push(root);
        int result=0;

        while(!que.empty()){

            int size=que.size();

            for(int i=0;i<size;i++){
                TreeNode* p=que.front();
                que.pop();result++;
                
                if(p->left)que.push(p->left);
                if(p->right)que.push(p->right);
            }
            
        }
        return result;
    }

2)递归法

1
2
3
4
5
6
7
class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root == NULL) return 0;//当前根结点自己算一个
        return 1 + countNodes(root->left) + countNodes(root->right);
    }
};

3)完全二叉树性质法

完全二叉树:除最后一层外,其余层全部铺满;且最后一层向左停靠

解法还不是太懂

This post is licensed under CC BY 4.0 by the author.