//递归
/**
* 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 root;
TreeNode* res = NULL;
if(root->val == val)
res = root;
if(res != NULL)
return res;
if(root->left != NULL){
res = searchBST(root->left,val);
if(res != NULL)//作用是一层一层的往上传递
return res;
}
if(root->right != NULL){
res = searchBST(root->right,val);
if(res != NULL)
return res;
}
return res;
}
};
一条语句
TreeNode* searchBST(TreeNode* root, int val) {
while(root != NULL && (root->val != val))
root = val>root->val?root->right:root->left;
return root;
}
//优点:因为不知道要查找的节点位置,就像第一种方法,待查找节点和遍历的方式很影响性能,几乎要全部遍历一遍才可以找到。第二种方法不需要遍历全部的节点。