leetcode 二叉树 空指针报错

avatar
作者
猴君
阅读量:0

 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;

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

这是为什么??

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!