AI助手生成的Golang代码

发表时间: 2024-03-04 16:07

AI用生成的二叉树层序遍历



package mainimport (	"fmt")// TreeNode represents a node in a binary treetype TreeNode struct {	Val   int	Left  *TreeNode	Right *TreeNode}// levelOrder performs level-order traversal of a binary treefunc levelOrder(root *TreeNode) [][]int {	if root == nil {		return [][]int{}	}	var result [][]int	queue := []*TreeNode{root} // using slice as a queue	for len(queue) > 0 {		levelSize := len(queue)		var level []int		for i := 0; i < levelSize; i++ {			node := queue[0]			queue = queue[1:] // dequeue			level = append(level, node.Val)			if node.Left != nil {				queue = append(queue, node.Left) // enqueue left child			}			if node.Right != nil {				queue = append(queue, node.Right) // enqueue right child			}		}		result = append(result, level)	}	return result}func main() {	// Example usage:	// Create a simple binary tree:	//      1	//     / \	//    2   3	//   / \	//  4   5	root := &TreeNode{		Val: 1,		Left: &TreeNode{			Val: 2,			Left: &TreeNode{				Val: 4,			},			Right: &TreeNode{				Val: 5,			},		},		Right: &TreeNode{			Val: 3,		},	}	// Perform level-order traversal	result := levelOrder(root)	// Print the result	for _, level := range result {		fmt.Println(level)	}}