[654].最大二叉树
func constructMaximumBinaryTree(nums []int) *TreeNode {
if len(nums)==0{
return nil
}
index := findMax(nums)
root := &TreeNode{
Val:nums[index],
Left:constructMaximumBinaryTree(nums[:index]),
Right:constructMaximumBinaryTree(nums[index+1:]),
}
return root
}
func findMax(nums []int)(index int){
for i, v := range nums {
if nums[index] < v{
index = i
}
}
return index
}
[617].合并二叉树
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
}
迭代,迭代有一点不理解的是为什么两次都是queue=queue[1:]
func mergeTrees(root1 *TreeNode, root2 *TreeNode) *TreeNode {
if root1 == nil {
return root2
}
if root2 == nil {
return root1
}
queue := make([]*TreeNode, 0)
queue = append(queue, root1)
queue = append(queue, root2)
for size := len(queue); size > 0; size = len(queue) {
node1 := queue[0]
queue = queue[1:]
node2 := queue[0]
queue = queue[1:]
node1.Val += node2.Val
if node1.Left != nil && node2.Left != nil {
queue = append(queue, node1.Left)
queue = append(queue, node2.Left)
}
if node1.Right != nil && node2.Right != nil {
queue = append(queue, node1.Right)
queue = append(queue, node2.Right)
}
if node1.Left == nil {
node1.Left = node2.Left
}
if node1.Right == nil {
node1.Right = node2.Right
}
}
return root1
}
[700].二叉搜索树中的搜索
func searchBST(root *TreeNode, val int) *TreeNode {
if root == nil {
return nil
}
if root.Val < val {
return searchBST(root.Right, val)
} else if root.Val > val {
return searchBST(root.Left, val)
}
return root
}
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].验证二叉搜索树
中序遍历做比较简单 一时间还没想到 prev做
func isValidBST(root *TreeNode) bool {
var prev *TreeNode
var trace func(node *TreeNode)bool
trace = func (node *TreeNode) bool{
if node ==nil{
return true
}
left:=trace(node.Left)
if prev!=nil&&node.Val<=prev.Val{
return false
}
prev =node
right:=trace(node.Right)
return left&&right
}
return trace(root)
}