[关闭]
@Xc-liu 2018-09-06T15:53:50.000000Z 字数 883 阅读 658

二叉搜索树的递归算法的一种错误写法

二叉搜索树 c++


出错代码

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. TreeNode* searchBST(TreeNode* root, int val) {
  13. if(root==NULL){
  14. return NULL;
  15. }else if(root->val>val){
  16. searchBST(root->left,val);
  17. }else if(root->val<val){
  18. searchBST(root->right,val);
  19. }else if(root->val==val){
  20. return root;
  21. }
  22. }
  23. };

出错原因分析

成功找到某一个节点以后,在return 的作用下返回上一次递归调用,但是此时在上层递归中函数将没有返回值从而导致报错

解决办法

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. TreeNode* searchBST(TreeNode* root, int val) {
  13. if(root==NULL){
  14. return NULL;
  15. }else if(root->val>val){
  16. return searchBST(root->left,val);//改为return
  17. }else if(root->val<val){
  18. return searchBST(root->right,val);//
  19. }else if(root->val==val){
  20. return root;
  21. }
  22. }
  23. };
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注