102. 二叉树的层序遍历

44 阅读1分钟

Problem: 102. 二叉树的层序遍历

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)

思路

广搜的思路,构造一个带深度的树记录深度

Code

func levelOrder(root *TreeNode) [][]int {
	if root == nil {
		return nil
	}
	type Tree struct {
		R    *TreeNode
		Deep int
	}
	tree := []*Tree{&Tree{root, 1}}
	res := make([][]int, 0)
	res = append(res, []int{root.Val})

	for len(tree) != 0 {

		t := tree[0]
		tree = tree[1:]
        if t.R.Left != nil {
			tree = append(tree, &Tree{t.R.Left, t.Deep + 1})
			if len(res) <= t.Deep {
				res = append(res, []int{t.R.Left.Val})
			} else {
				res[t.Deep] = append(res[t.Deep], t.R.Left.Val)
			}
		}
		if t.R.Right != nil {
			tree = append(tree, &Tree{t.R.Right, t.Deep + 1})
			if len(res) <= t.Deep {
				res = append(res, []int{t.R.Right.Val})
			} else {
				res[t.Deep] = append(res[t.Deep], t.R.Right.Val)
			}
		}

		
	}
	return res
}