欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode 700. Search in a Binary Search Tree

程序员文章站 2022-06-08 09:31:00
...
/**
 * 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->val==val)return root;
        TreeNode* p;
        p = root;
        while(p!=NULL&&p->val!=val)
        {
            if(p->val>val)p=p->left;
            else if(p->val<val)p=p->right;
        }
        return p;
    }
};