LeetCode 700 Search in a Binary Search Tree

Tag: 二叉搜索树 LeetCode Posted on 2022-02-07 13:19:11 Edited on 2022-02-07 13:22:40 Views: 159

概述

https://leetcode.com/problems/search-in-a-binary-search-tree/submissions/

递归法

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

迭代法

class Solution {
public:
    TreeNode* searchBST(TreeNode* root, int val) {
        auto c = root;
        while (c && c->val != val) {
            if (c->val > val) {
                c = c->left;
            } else {
                c = c->right;
            }
        }
        return c;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/