今日题目:
530.二叉搜索树的最小绝对差
501.二叉搜索树中的众数
236. 二叉树的最近公共祖先
今日总结
二叉搜索树可以当作有序的数组来处理,要能够利用好其特性,避免遍历整个二叉树。501中记录多个众数时的清楚操作很关键,需要牢记。在写递归的时候要思考清楚整个递归函数返回的是什么(比如一棵子树),把函数当作一个整体处理。
530.二叉搜索树的最小绝对差
要点
- 把二叉搜索树当作一个有序的数组来思考
- 学会在二叉树中使用双指针
代码:
func getMinimumDifference(root *TreeNode) int {
var pre *TreeNode
min := math.MaxInt64
var travel func(node *TreeNode)
travel = func(node *TreeNode) {
if node == nil {
return
}
travel(node.Left)
if pre != nil && node.Val - pre.Val < min {
min = node.Val - pre.Val
}
pre = node
travel(node.Right)
}
travel(root)
return min
}
501.二叉搜索树中的众数
要点:
- 二叉树中使用双指针
- 注意这题中时如何遍历一遍就找到多个众数的。当最大频次更新时,将mode切片清空,因为之前的结果都没用了。
func findMode(root *TreeNode) []int {
res := make([]int, 0)
count := 1
max := 1
var pre *TreeNode
var travel func(node *TreeNode)
travel = func(node *TreeNode) {
if node == nil {
return
}
travel(node.Left)
if pre != nil && pre.Val == node.Val{
count++
} else{
count = 1
}
if count >= max{
if count > max && len(res) > 0 { // 减少了开头的一次重新赋值
res = []int{node.Val}
} else{
res = append(res, node.Val)
}
max = count
}
pre = node
travel(node.Right)
}
travel(root)
return res
}
236. 二叉树的最近公共祖先
要点:
- 这题挺有难度的,首先要思考清楚如何找公共祖先节点
- 要考虑q,p本身为公共祖先节点的情况
- 递归时将函数当作整体来思考,代码中left就是包含了p,q的左子树,right是包含p,q的右子树,如果left和right都不为空是说明找到了公共祖先
- 那么是不是最近的呢?其实本题中因为p q不重复,所以当3成立时必然为仅有的公共祖先,因为唯一, 所以必然最近
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil || root == p ||root ==q {
return root
}
left := lowestCommonAncestor(root.Left, p, q)
right := lowestCommonAncestor(root.Right, p, q)
if left ==nil{
return right
}
if right == nil {
return left
}
return root
}