题目
给定二叉搜索树(BST)的根节点 root 和一个整数值 val。
你需要在 BST 中找到节点值等于 val 的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 null 。
示例
输入:root = [4,2,7,1,3], val = 2
输出:[2,1,3]
解析
首先注意本题是二叉搜索树,即有序的(之前的都是乱序的),这样其实就有点二分查找的意思了。
递归法:
/**
* 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 {
return root
}
var res *TreeNode
if root.Val > val {
res = searchBST(root.Left, val)
} else if root.Val < val {
res = searchBST(root.Right, val)
} else {
return root
}
return res
}
至于迭代法也比较简单,暴力解就可以
/**
* 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.Left
} else if root.Val < val {
root = root.Right
} else {
break
}
}
return root
}