Leetcode:700. 二叉搜索树中的搜索

Leetcode:700. 二叉搜索树中的搜索

Leetcode:700. 二叉搜索树中的搜索

Talk is cheap . Show me the code .

递归写法:

/**
 * 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;
        if(root->val==val) return root;
        return root->val>val?searchBST(root->left,val):searchBST(root->right,val);
    }
};

迭代写法:

/**
 * 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) {
        while(root!=NULL){
            if(root->val==val) break;
            root->val>val?root=root->left:root=root->right;
        }
        return root;
    }
};
posted @ 2020-02-28 21:17  Herman·H  阅读(130)  评论(0编辑  收藏  举报