LeetCode654. 最大二叉树Golang版
1. 问题描述
给定一个不含重复元素的整数数组 nums 。一个以此数组直接递归构建的 最大二叉树 定义如下:
二叉树的根是数组 nums 中的最大元素。
左子树是通过数组中 最大值左边部分 递归构造出的最大二叉树。
右子树是通过数组中 最大值右边部分 递归构造出的最大二叉树。
返回有给定数组 nums 构建的 最大二叉树 。
2. 思路
递归构造二叉树模板题
- 找到当前节点索引index,根据该索引构造出node
- 根据数组递归构建二叉树
node.Left = constructMaximumBinaryTree(nums[:index])
node.Right = constructMaximumBinaryTree(nums[index+1:])
3. 代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func constructMaximumBinaryTree(nums []int) *TreeNode {
return maxTree(nums, 0, len(nums))
}
func maxTree(nums []int, left int, right int) *TreeNode {
if left >= right {
return nil
}
maxIndex := left
for i := left + 1; i < right; i++ {
if nums[i] > nums[maxIndex] {
maxIndex = i
}
}
root := &TreeNode {
Val : nums[maxIndex],
Left : nil,
Right : nil,
}
root.Left = maxTree(nums, left, maxIndex )
root.Right = maxTree(nums, maxIndex + 1, right)
return root
}
// func findMax(nums []int, left int, right int) int {
// max := nums[left]
// maxIndex := left
// for i := left+1; i <= right; i++ {
// if nums[i] > max {
// max = nums[i]
// maxIndex = i
// }
// }
// return maxIndex
// }
3.2. 另一种写法
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func constructMaximumBinaryTree(nums []int) *TreeNode {
return maxTree(nums, 0, len(nums) - 1)
}
func maxTree(nums []int, left int, right int) *TreeNode {
if left > right {
return nil
}
maxIndex := left
for i := left + 1; i <= right; i++ {
if nums[i] > nums[maxIndex] {
maxIndex = i
}
}
root := &TreeNode {
Val : nums[maxIndex],
Left : nil,
Right : nil,
}
root.Left = maxTree(nums, left, maxIndex - 1 )
root.Right = maxTree(nums, maxIndex + 1, right)
return root
}
3.3. 构造二叉树模板写法
/**
* 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
}
index := max(nums)
node := &TreeNode {
Val : nums[index],
}
node.Left = constructMaximumBinaryTree(nums[:index])
node.Right = constructMaximumBinaryTree(nums[index+1:])
return node
}
func max(nums []int) int {
var maxIndex int
for i := 1; i < len(nums); i++ {
if nums[i] > nums[maxIndex] {
maxIndex = i
}
}
return maxIndex
}