Skip to content
本页目录

0700-二叉搜索树中的搜索

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

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

例如,

给定二叉搜索树:

        4
       / \
      2   7
     / \
    1   3

和值: 2 你应该返回如下子树:

      2     
     / \   
    1   3

在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL。

思路

二叉搜索树,左节点的值都小于右节点,根据这个特性可以递归查找目标值

参考代码

csharp
public class Solution {
    public TreeNode SearchBST(TreeNode root, int val) {
    	if(root == null){
    		return null;
    	}
    	if(val < root.val){
    		return SearchBST(root.left, val);
    	}
    	else if(val > root.val){
    		return SearchBST(root.right, val);
    	}
    	else{
    		return root;
    	}
    }
}

思路2:迭代

方法同递归,不停的更新 root 的值

csharp
public class Solution {
    public TreeNode SearchBST(TreeNode root, int val) {
        while(root != null){
            if(root.val == val){
                return root;
            }
            else{
                if(val < root.val){
                    root = root.left;
                }
                else{
                    root = root.right;
                }
            }
        }
        return null;
    }
}

Released under the MIT License.