1.验证二叉搜索树
https://leetcode-cn.com/problems/validate-binary-search-tree/
1.用中序遍历,如果结果是升序的,那就是二叉排序树
func isValidBST(root *TreeNode) bool {
stack := []*TreeNode {}
inorder := math.MinInt64
for len(stack) > 0 || root != nil {
for root != nil {
stack = append(stack, root)
root = root.Left
}
root = stack[len(stack) - 1]
stack = stack[:len(stack) - 1]
if root.Val <= inorder {
return false
}
inorder = root.Val
root = root.Right
}
return true
}
2.递归函数判断
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)
}
2.二叉搜索树的最近公共祖先
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
1.路径查找
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
}
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
}
3.二叉树的最近公共祖先
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
二叉树的遍历: