代码随想录算法训练营Day23 | 530.二叉搜索树的最小绝对差、501.二叉搜索树中的众数、236.二叉树的最近公共祖先

42 阅读1分钟

LeetCode题目

530.二叉搜索树的最小绝对差

题目链接:Minimum Absolute Difference in BST - LeetCode

代码如下:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}

func getMinimumDifference(root *TreeNode) int {
	result := math.MaxInt
	var pre *TreeNode
	var traversal func(cur *TreeNode)
	traversal = func(cur *TreeNode) {
		if cur == nil {
			return
		}
		traversal(cur.Left)
		if pre != nil {
			result = min(result, cur.Val-pre.Val)
		}
		pre = cur
		traversal(cur.Right)
	}
	traversal(root)
	return result
}

501.二叉搜索树中的众数

题目链接:Find Mode in Binary Search Tree - LeetCode

代码如下:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func findMode(root *TreeNode) []int {
	res := make([]int, 0)
	count := 0
	maxCount := 0
	var pre *TreeNode
	var searchBST func(cur *TreeNode)
	searchBST = func(cur *TreeNode) {
		if cur == nil {
			return
		}
		searchBST(cur.Left)
		if pre == nil {
			count = 1
		} else if pre.Val == cur.Val {
			count++
		} else {
			count = 1
		}
		pre = cur
		if count == maxCount {
			res = append(res, cur.Val)
		}
		if count > maxCount {
			maxCount = count
			res = res[0:0]
			res = append(res, cur.Val)
		}
		searchBST(cur.Right)
	}
	searchBST(root)
	return res
}

236.二叉树的最近公共祖先

题目链接:Lowest Common Ancestor of a Binary Tree - LeetCode

代码如下:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
	if root == p || root == q || root == nil {
		return root
	}
	left := lowestCommonAncestor(root.Left, p, q)
	right := lowestCommonAncestor(root.Right, p, q)
	if left != nil && right != nil {
		return root
	}
	if left == nil && right != nil {
		return right
	} else if left != nil && right == nil {
		return left
	} else {
		return nil
	}
}

总结

  1. 二叉树如何自底向上查找,回溯,二叉树回溯的过程就是自底向上
  2. 后序遍历(左右中)就是天然的回溯过程,可以根据左右子树的返回值,来处理中间节点