💪💪💪此系列仅为记录本人补充学习数据结构相关知识,有兴趣的,大家可以共同学习👏👏👏
二叉搜索树BST相关说明
1、二叉搜索树是一个有序树
2、若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
3、若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
4、它的左、右子树也分别为二叉搜索树
[= 验证二叉搜索树 =]
题目描述
解题思路
根据二叉搜索树的特点,一一验证即可
解题方法
func isValidBST(root *TreeNode) bool {
return helper(root, math.MinInt64, math.MaxInt64)
}
func helper(root *TreeNode, lower, upper int) bool {
if root == nil {
return true
}
if root.Val <= lower || root.Val >= upper {
return false
}
return helper(root.Left, lower, root.Val) && helper(root.Right, root.Val, upper)
}
[= 二叉搜索树的最近公共祖先 =]
题目描述
解题方法
func lowestCommonAncestor(root, p, q *TreeNode) (ancestor *TreeNode) {
pathP := getPath(root, p)
pathQ := getPath(root, q)
for i := 0; i < len(pathP) && i < len(pathQ) && pathP[i] == pathQ[i]; i++ {
ancestor = pathP[i]
}
return
}
func getPath(root, target *TreeNode) (path []*TreeNode) {
node := root
for node != target {
path = append(path, node)
if target.Val < node.Val {
node = node.Left
} else {
node = node.Right
}
}
path = append(path, node)
return
}
[= 两数之和 IV - 输入BST =]
题目描述
解题思路
有点类似路径总和,只不过这个只需找到两个节点只和就行
遍历搜索二叉树,将所有节点值存入hash表
在递归遍历的同时,判断当前值与目标值的差是否存在hash 如果有返回 true
解题方法
var target int
var h map[int]bool
var res bool
func findTarget(root *TreeNode, k int) bool {
h = map[int]bool{}
res = false
target = k
dfs(root)
return res
}
func dfs(root *TreeNode) {
if root != nil {
dfs(root.Left)
if h[target-root.Val] {
res = true
return
}
h[root.Val] = true
dfs(root.Right)
}
}