算法记录Day 20 | 二叉树part07

55 阅读1分钟

算法记录Day 20 | 二叉树part07

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

题目链接:530. 二叉搜索树的最小绝对差

题解
import "math"

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

var pre *TreeNode
var res = math.MaxInt32

func getMinimumDifference(root *TreeNode) int {
	res = math.MaxInt32
	pre = nil
	traversal(root)
	return res
}

func traversal(cur *TreeNode) {
	if cur == nil {
		return
	}
	traversal(cur.Left)
	if pre != nil {
		res = int(math.Min(float64(res), float64(cur.Val-pre.Val)))
	}
	pre = cur
	traversal(cur.Right)
}

LeetCode 501.二叉搜索树中的众数

题目链接:501. 二叉搜索树中的众数

题解
var max int
var resutl []int
var cur int
var counter int

func findMode(root *TreeNode) []int {
	resutl, max, cur, counter = []int{}, 1, 0, 0
	dfs(root)
	return resutl
}

func dfs(root *TreeNode) {
	if root != nil {
		dfs(root.Left)
		if root.Val != cur {
			counter = 0
		}
		counter++
		if max < counter {
			max = counter
			resutl = []int{root.Val}
		} else if max == counter {
			resutl = append(resutl, root.Val)
		}
		cur = root.Val
		dfs(root.Right)
	}
}

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

题目链接:236. 二叉树的最近公共祖先

题解
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
	if root == nil {
		return root
	}
	// 找到了节点
	if root == p || root == q {
		return root
	}
	// dfs后序遍历
	left := lowestCommonAncestor(root.Left, p, q)
	right := lowestCommonAncestor(root.Right, p, q)
	// 如果两个都不为空就是最近公共祖先节点
	if left != nil && right != nil {
		return root
	}
	if left != nil {
		return left
	}
	if right != nil {
		return right
	}
	return nil
}