[leetcode]700. Search in a Binary Search Tree

[leetcode]700. Search in a Binary Search Tree


Analysis

一个有台风的周末~—— [中午吃什么外卖呢~]

Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node’s value equals the given value. Return the subtree rooted with that node. If such node doesn’t exist, you should return NULL.
简单的二叉树搜索
发现一个问题,循环貌似比递归快,可以看一下这篇博客:
https://www.cnblogs.com/BeyondAnyTime/archive/2012/05/19/2508807.html

Implement

方法一(recursive)

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

方法二(iteration)

/**
 * 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)
            return NULL;
        while(root){
            if(root->val == val)
                return root;
            else if(root->val > val)
                root = root->left;
            else
                root = root->right;
        }
        return NULL;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81152939