Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

102. 二叉树的层序遍历 #53

Open
yankewei opened this issue Aug 23, 2020 · 1 comment
Open

102. 二叉树的层序遍历 #53

yankewei opened this issue Aug 23, 2020 · 1 comment
Labels
中等 题目难度为中等 广度优先搜索 题目包含广度优先搜索解法 题目类型为树结构

Comments

@yankewei
Copy link
Owner

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

示例:

二叉树:[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]
@yankewei yankewei added 中等 题目难度为中等 广度优先搜索 题目包含广度优先搜索解法 题目类型为树结构 labels Aug 23, 2020
@yankewei
Copy link
Owner Author

广度优先搜索

二叉树的层序遍历,很典型的广度优先搜索,就是遍历树的每一层。需要用到队列

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func levelOrder(root *TreeNode) [][]int {
    // 声明返回值
    var ret [][]int
    // 先把基本的case排除
    if root == nil {
        return ret
    }
    // 用来保存遍历的队列
    queue := []*TreeNode{root}
    // 用来保存临时队列,当queue为空的时候表示当前的层次已遍历完,把tmpQueue赋值给queue继续遍历即可,这时层次+1
    tmpQueue := []*TreeNode{}
    // 保存层次的数组
    var subRet []int
    for len(queue) != 0 {
        subRet = append(subRet, queue[0].Val)
	if queue[0].Left != nil {
	    tmpQueue = append(tmpQueue, queue[0].Left)
        }
         if queue[0].Right != nil {
	    tmpQueue = append(tmpQueue, queue[0].Right)
	}
        queue = queue[1:]
	if len(queue) == 0 {
	    ret = append(ret, subRet)
	    subRet = []int{}
	    queue = tmpQueue
	    tmpQueue = []*TreeNode{}
	}
    }
    return ret
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 题目难度为中等 广度优先搜索 题目包含广度优先搜索解法 题目类型为树结构
Projects
None yet
Development

No branches or pull requests

1 participant