力扣-700 二叉搜索树中的搜索

力扣-700 二叉搜索树中的搜索

AC Code

Method 1. inorder

class Solution {
public:
    TreeNode* searchBST(TreeNode* root, int val) {
        TreeNode *curNode = root;
        stack<TreeNode*> st;
        while(!st.empty() || curNode){
            while(curNode){
                if(curNode->val == val) return curNode;
                st.push(curNode);
                curNode = curNode->left;
            }
            curNode = st.top();
            st.pop();
            if(curNode->val == val) return curNode;
            curNode = curNode->right;
        }
        return NULL;
    }
};

Method 2. recursion

class Solution {
public:
    TreeNode* searchBST(TreeNode* root, int val) {
        if(!root) return NULL;
        if(root->val == val) return root;
        return root->val > val ? searchBST(root->left,val) : searchBST(root->right,val);
    }
};

你可能感兴趣的:(LeetCode,leetcode,算法,二叉搜索树)