跳至主要內容

700, 二叉搜索树中的搜索

Mike大约 2 分钟binary treeeasybinary treebinary search tree

一、题目描述

给定二叉搜索树(BST)的根节点root和一个整数值val

你需要在BST中找到节点值等于val的节点。返回以该节点为根的子树。如果节点不存在,则返回null

示例 1

输入: root = [4, 2, 7, 1, 3], val = 2
输出: [2, 1, 3]

示例 2

输入: root = [4, 2, 7, 1, 3], val = 5
输出: []

提示

  • 树中节点数在[1, 5000]范围内
  • 1 <= Node.val <= 10⁷
  • root是二叉搜索树
  • 1 <= val <= 10⁷

相关主题

  • 二叉搜索树
  • 二叉树

二、题解

#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Rc<RefCell<TreeNode>>>,
    pub right: Option<Rc<RefCell<TreeNode>>>,
}

impl TreeNode {
    #[inline]
    pub fn new(val: i32) -> Self {
        TreeNode {
            val,
            left: None,
            right: None,
        }
    }
}

方法 1: 递归

///
/// 时间复杂度: O(n)
/// 空间复杂度: O(n)
///
pub fn search_bst(root: Option<Rc<RefCell<TreeNode>>>, val: i32) -> Option<Rc<RefCell<TreeNode>>> {
    const SEARCH: fn(Option<Rc<RefCell<TreeNode>>>, i32) -> Option<Rc<RefCell<TreeNode>>> =
        |root, val| match root {
            None => None,
            Some(curr) => {
                let curr_val = curr.borrow().val;
                let left = curr.borrow().left.clone();
                let right = curr.borrow().right.clone();

                if val > curr_val {
                    SEARCH(right, val)
                } else if val < curr_val {
                    SEARCH(left, val)
                } else {
                    Some(curr)
                }
            }
        };

    SEARCH(root, val)
}

方法 2: 迭代

///
/// 时间复杂度: O(n)
/// 空间复杂度: O(1)
///
pub fn search_bst(mut root: Option<Rc<RefCell<TreeNode>>>, val: i32) -> Option<Rc<RefCell<TreeNode>>> {
    while let Some(curr) = root {
        let curr_val = curr.borrow().val;
        let left = curr.borrow().left.clone();
        let right = curr.borrow().right.clone();

        if val > curr_val {
            root = right;
        } else if val < curr_val {
            root = left;
        } else {
            return Some(curr);
        }
    }

    None
}