• leetcode二叉树系列通用输入定义


    日常我们在leetcode上刷题的时候,都是核心代码模式,并不知道如何构造参数,以及自己写输入输出调试的时候该如何处理,在这里进行一个整理。
    下面以二叉树的层序遍历为示例来写:

    package main
    
    import (
    	"container/list"
    	"fmt"
    )
    
    type TreeNode struct {
    	Val   int
    	Left  *TreeNode
    	Right *TreeNode
    }
    
    func levelOrder(root *TreeNode) [][]int {
    	result := [][]int{}
    	if root == nil {
    		return result
    	}
    
    	queue := list.New()
    	queue.PushBack(root)
    
    	for queue.Len() > 0 {
    		levelSize := queue.Len()
    		levelValues := []int{}
    
    		for i := 0; i < levelSize; i++ {
    			node := queue.Remove(queue.Front()).(*TreeNode)
    			levelValues = append(levelValues, node.Val)
    
    			if node.Left != nil {
    				queue.PushBack(node.Left)
    			}
    			if node.Right != nil {
    				queue.PushBack(node.Right)
    			}
    		}
    
    		result = append(result, levelValues)
    	}
    
    	return result
    }
    
    func main() {
    	// 创建一个示例二叉树
    	root := &TreeNode{Val: 3}
    	root.Left = &TreeNode{Val: 9}
    	root.Right = &TreeNode{Val: 20}
    	root.Right.Left = &TreeNode{Val: 15}
    	root.Right.Right = &TreeNode{Val: 7}
    
    	// 执行层次遍历
    	result := levelOrder(root)
    
    	// 输出结果
    	fmt.Println(result)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    或者说是输入一个数组,然后构造二叉树,以输入有序数组(中序为例):

    func sortedArrayToBST(nums []int, start, end int) *TreeNode {
    	if start > end {
    		return nil
    	}
    
    	mid := (start + end) / 2
    	root := &TreeNode{Val: nums[mid]}
    	root.Left = sortedArrayToBST(nums, start, mid-1)
    	root.Right = sortedArrayToBST(nums, mid+1, end)
    	return root
    }
    
    func main() {
    	arr := []int{1, 2, 3, 4, 5, 6, 7}
    	result := sortedArrayToBST(arr, 0, len(arr)-1)
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  • 相关阅读:
    代码中统一异常如何处理,才能让代码更清晰
    新人笔记1
    P1036 [NOIP2002 普及组] 选数
    高阶python | is 与 ==
    Redis--list列表
    Ubuntu Server搭建个人服务器
    C++-逻辑语句
    2022-10-21 解决vuex报错:Cannot read properties of undefined (reading ‘state‘)“
    docker network create命令
    我招基础初级运维实习生的面试题
  • 原文地址:https://blog.csdn.net/midi666/article/details/134003451