700. Search in a Binary Search Tree

1.問題

  • 給予一個BST, 找出sub tree

2.想法

  • Inorder traversal

3.程式碼

/**
 * 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;
        }
        
        TreeNode* left = searchBST(root->left, val);
        if (left != NULL && left->val == val) {
            return left;
        }
        if (root->val == val) {
            return root;
        }
        TreeNode* right = searchBST(root->right, val);
        if (right != NULL && right->val == val) {
            return right;
        }
        return NULL;
    }
};

4.Performance

Last updated