LeetCode700. 二叉搜索树中的搜索Golang版

LeetCode700. 二叉搜索树中的搜索Golang版

1. 问题描述

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

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

2. 思路

2.1. 递归思路

  1. 确定递归函数参数和返回值
func *TreeNode searchBST(root *TreeNode, val int)
  1. 确定终止条件
if root == nil || root.Val == val {
          
   
		return root
	}
  1. 确定单层递归逻辑
if root.Val > val, 搜索左子树
	if root.Val < val, 搜索右子树
	return nil

2.2. 迭代思路

一般二叉树迭代法,使用栈来模拟深度优先遍历,使用队列模拟广度优先遍历;二叉搜索树由于其节点的有序性,不需要辅助栈或队列就可以写出迭代法。 一般二叉树递归过程中,会有回溯过程,一个分支走到头了,要进行掉头,再走左右分支;对于二叉搜索树,不需要回溯的过程,节点有序性可以确定搜索的方向,也就是搜索某一特定节点时,搜索路径是提前规划好的。

3. 代码

3.1. 递归代码

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func searchBST(root *TreeNode, val int) *TreeNode {
          
   
    if root == nil || root.Val == val {
          
   
        return root
    }

    if root.Val > val {
          
   
        return searchBST(root.Left, val)
    }

    if root.Val < val {
          
   
        return searchBST(root.Right, val)
    }

    return nil
}

3.2. 迭代代码

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func searchBST(root *TreeNode, val int) *TreeNode {
          
   
    for root != nil {
          
   
        if root.Val < val {
          
   
            root = root.Right
        } else if root.Val > val {
          
   
            root = root.Left
        } else {
          
   
            return root
        }
    }
    return nil
}
经验分享 程序员 微信小程序 职场和发展