LeetCode 700 Search in a Binary Search Tree

标签: 二叉搜索树 LeetCode 发布于:2022-02-07 13:19:11 编辑于:2022-02-07 13:22:40 浏览量:933

概述

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/