自学内容网 自学内容网

leetcode 二叉树 空指针报错

 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 geNum(TreeNode* cur){//确定递归函数参数和返回值
        if(cur==nullptr) return 0;
        //确定终止条件
        int leftNum=0,rightNum=0;
        TreeNode* left=cur->left;
        TreeNode* right=cur->right;
        while(left){
            leftNum++;
            left=left->left;
        }
        while(right){
            rightNum++;
            right=right->right;
        }
        if(leftNum==rightNum) return (2<<leftNum)-1;

        //单层递归逻辑
        int leftTreeNum=geNum(cur->left);
        int rightTreeNum=geNum(cur->right);
        int midTreeNum=leftTreeNum+rightTreeNum+1;

        return midTreeNum;
    }
    int countNodes(TreeNode* root) {
        
         return geNum(root);
    }
};

未通过的代码:

/**
 * 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 geNum(TreeNode* cur){//确定递归函数参数和返回值
        //if(cur==nullptr) return 0;
        //确定终止条件
        int leftNum=0,rightNum=0;
        TreeNode* left=cur->left;
        TreeNode* right=cur->right;
        while(left){
            leftNum++;
            left=left->left;
        }
        while(right){
            rightNum++;
            right=right->right;
        }
        if(leftNum==rightNum) return (2<<leftNum)-1;

        //单层递归逻辑
        int leftTreeNum=geNum(cur->left);
        int rightTreeNum=geNum(cur->right);
        int midTreeNum=leftTreeNum+rightTreeNum+1;

        return midTreeNum;
    }
    int countNodes(TreeNode* root) {
        if(root==nullptr) return 0;
         return geNum(root);
    }
};

问题:

在countNodes函数中添加的代码:

if(root==nullptr) return 0;

好像没有用似的,必须在递归函数中添加这行代码才不会报错。

这是为什么??


原文地址:https://blog.csdn.net/m0_73924943/article/details/140672508

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!