LeetCode BinaryTree Level Order Traversal (golang)

Problem
在这里插入图片描述
Analysis Process

1.Recursive
use DFS
We can first traversal the binary tree in order (around the root), at the same time, record the level of the node, and define an array for each level, and then put the value of the accessed node into the array of the corresponding level

2.BFS
we can use the data structure of Queue and we can initialize the root node to Queue and do the BFS by consuming the tail and inserting the head

Code
1.Recursive

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func levelOrder(root *TreeNode) [][]int {
    return dfs(root, 0, [][]int{})
}

func dfs(root *TreeNode, level int, res [][]int) [][]int {
	if root == nil {
		return res
	}
	if len(res) == level {
		res = append(res, []int{root.Val})
	} else {
		res[level] = append(res[level], root.Val)
	}
	res = dfs(root.Left, level+1, res)
	res = dfs(root.Right, level+1, res)
    return res
}

2.BFS

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func levelOrder(root *TreeNode) [][]int {
	var result [][]int
	if root == nil {
		return result
	}
    //Define a two-way queue
	queue := list.New()
    // The header inserts the root node
	queue.PushFront(root)
    // BFS
	for queue.Len() > 0 {
		var current []int
		listLength := queue.Len()
		for i := 0; i < listLength; i++ {
		    // Consumption of the tail
            // queue.Remove(queue.Back()).(*TreeNode):Remove the last element and convert it to the TreeNode type
			node := queue.Remove(queue.Back()).(*TreeNode)
			current = append(current, node.Val)
			if node.Left != nil {
			    //Insert the head
				queue.PushFront(node.Left)
			}
			if node.Right != nil {
				queue.PushFront(node.Right)
			}
		}
		result = append(result, current)
	}
	return result
}

猜你喜欢

转载自blog.csdn.net/qq_46595591/article/details/107707440