Day20 二叉树Part06
654. 最大二叉树 - 力扣(LeetCode)
递归构建即可
func constructMaximumBinaryTree(nums []int) *TreeNode {
if len(nums) == 0 {
return nil
}
var max int
for i := 1; i < len(nums); i++ {
if nums[max] < nums[i] {
max = i
}
}
temp := &TreeNode{
Val: nums[max],
Left: constructMaximumBinaryTree(nums[0: max]),
Right: constructMaximumBinaryTree(nums[max+1:]),
}
return temp
}
617. 合并二叉树 - 力扣(LeetCode)
一起进行遍历拼接
func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode {
if root1 == nil {
return root2
}
if root2 == nil {
return root1
}
root1.Val += root2.Val
root1.Left = mergeTrees(root1.Left, root2.Left)
root1.Right = mergeTrees(root1.Right, root2.Right)
return root1
}
700. 二叉搜索树中的搜索 - 力扣(LeetCode)
利用特性,超简单,第一次做的时候还没注意到是二叉搜索树
func searchBST(root *TreeNode, val int) *TreeNode {
for root != nil { // 只要不为空
if val == root.Val {
return root // 找到对应的值
}
if val < root.Val {
root = root.Left // 小于节点,在左边
} else {
root = root.Right // 大于节点在右边
}
}
return nil
}
98. 验证二叉搜索树 - 力扣(LeetCode)
左边最大的必定小于右边最小的即可,或者进行中序遍历,只要有序即可
func isValidBST(root *TreeNode) bool {
var f func(*TreeNode, int, int) bool
f = func(r *TreeNode, min int, max int) bool {
if r == nil {
return true
}
if r.Val <= min || r.Val >= max {
return false
}
return f(r.Left, min, r.Val) && f(r.Right, r.Val, max)
}
return f(root, math.MinInt, math.MaxInt)
}