1 class Solution { 2 public: 3 int max_; 4 int depth=1; 5 int maxDepth(TreeNode* root) { 6 7 if(root->left!=NULL) 8 { 9 depth++; 10 maxDepth(root->left); 11 depth--; 12 } 13 if(root->right!=NULL) 14 { 15 depth++; 16 maxDepth(root->right); 17 depth--; 18 } 19 max_=max(max_,depth); 20 } 21 return max_; 22 };
一直给我报错member access within null pointer of type 'struct TreeNode',我就纳闷了我也判断空指针了啊。为啥呢?然后突然发现貌似没判断root,失误失误。
所以最前面加上一行if(root!=NULL)就全部解决了啊!!!!!!