LeetCode题目
654.最大二叉树
题目链接:Maximum Binary Tree - LeetCode
代码如下:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func constructMaximumBinaryTree(nums []int) *TreeNode {
if len(nums) == 0 {
return nil
}
root := &TreeNode{
Val: 0,
Left: nil,
Right: nil,
}
if len(nums) == 1 {
root.Val = nums[0]
return root
}
maxIndex := -1
maxValue := -1
for index, value := range nums {
if value > maxValue {
maxIndex = index
maxValue = value
}
}
root.Val = maxValue
leftNums := nums[:maxIndex]
rightNums := nums[maxIndex+1:]
root.Left = constructMaximumBinaryTree(leftNums)
root.Right = constructMaximumBinaryTree(rightNums)
return root
}
617.合并二叉树
题目链接:Merge Two Binary Trees - LeetCode
代码如下:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
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.二叉搜索树中的搜索
题目链接:Search in a Binary Search Tree - LeetCode
代码如下:
递归法
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func searchBST(root *TreeNode, val int) *TreeNode {
if root == nil || root.Val == val {
return root
}
var result *TreeNode
if root.Val > val {
result = searchBST(root.Left, val)
} else {
result = searchBST(root.Right, val)
}
return result
}
迭代法
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func searchBST(root *TreeNode, val int) *TreeNode {
for root != nil {
if root.Val > val {
root = root.Left
} else if root.Val < val {
root = root.Right
} else {
return root
}
}
return nil
}
98.验证二叉搜索树
题目链接:Validate Binary Search Tree - LeetCode
代码如下:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isValidBST(root *TreeNode) bool {
var pre *TreeNode
var travel func(node *TreeNode) bool
travel = func(node *TreeNode) bool {
if node == nil {
return true
}
left := travel(node.Left)
if pre != nil && pre.Val >= node.Val {
return false
}
pre = node
right := travel(node.Right)
return left && right
}
return travel(root)
}
总结
- 二叉搜索树满足以下条件
- 对于根节点,左子树中所有节点的值 < 根节点的值 < 右子树中所有节点的值
- 任意节点的左、右子树也是二叉搜索树,即同样满足条件1.
- 二叉搜索树的中序遍历序列是升序的,因此遇到二叉搜索树问题,多考虑使用中序遍历