Skip to content

Latest commit

 

History

History
34 lines (29 loc) · 745 Bytes

32 - I. 从上到下打印二叉树.md

File metadata and controls

34 lines (29 loc) · 745 Bytes

解题思路

1. 层序遍历

使用队列 q,以切片末尾作为队尾,以切片最小索引作为队首, 每次 q 出队队首元素,进行判断,并将左右子节点加入队尾

func levelOrder(root *TreeNode) []int {
    q := make([]*TreeNode, 0)
    ans := []int{}
    if root != nil {
        q = append(q, root)
    }
    for len(q) != 0 {
        // 出队队首元素
        top := q[0]
        q = q[1:]
        ans = append(ans, top.Val)
        // 如果左右儿子存在,入队
        if top.Left != nil {
            q = append(q, top.Left)
        }
        if top.Right != nil {
            q = append(q, top.Right)
        }
    }
    return ans
}