@Xc-liu
2018-09-06T15:53:50.000000Z
字数 883
阅读 670
二叉搜索树
c++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root==NULL){
return NULL;
}else if(root->val>val){
searchBST(root->left,val);
}else if(root->val<val){
searchBST(root->right,val);
}else if(root->val==val){
return root;
}
}
};
成功找到某一个节点以后,在return 的作用下返回上一次递归调用,但是此时在上层递归中函数将没有返回值从而导致报错
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root==NULL){
return NULL;
}else if(root->val>val){
return searchBST(root->left,val);//改为return
}else if(root->val<val){
return searchBST(root->right,val);//
}else if(root->val==val){
return root;
}
}
};