[leetcode]700. 二叉搜索树中的搜索

1.题目:
给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。

给定二叉搜索树:

        4
       / \
      2   7
     / \
    1   3

和值: 2

2.代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct TreeNode* searchBST(struct TreeNode* root, int val) {
    struct TreeNode *p=root;
    while(p){
        if(p->val==val)
            return p;
        else if(p->val<val)
            p=p->right;
        else
            p=p->left;
    }
    return NULL;
}

3.知识点:

二叉排序树遍历。

猜你喜欢

转载自blog.csdn.net/MJ_Lee/article/details/88145833