Swift - LeetCode - 二叉树的层次遍历

题目

二叉树的层次遍历

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

示例:


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

3

  / \

  9  20

    /  \

  15  7

返回其层次遍历结果:

[

  [3],

  [9,20],

  [15,7]

]

代码:

/**

* Definition for a binary tree node.

* public class TreeNode {

*    public var val: Int

*    public var left: TreeNode?

*    public var right: TreeNode?

*    public init(_ val: Int) {

*        self.val = val

*        self.left = nil

*        self.right = nil

*    }

* }

*/

class Solution {

    func levelOrder(_ root: TreeNode?) -> [[Int]] {

        var intList:[[Int]] = [[Int]]()

        var nodeList:[TreeNode] = [TreeNode]()

        guard let root = root else {

            return intList

        }

        nodeList.append(root)

        while nodeList.isEmpty == false {

            var count = nodeList.count

            var temp = [Int]()

            while count != 0 {

                let node = nodeList.removeFirst()

                temp.append(node.val)

                if node.left != nil {
                    nodeList.append(node.left!)
                }

                if node.right != nil {
                    nodeList.append(node.right!)
                }
                count = count - 1
            }
            intList.append(temp)
        }
              return intList
    }

}

你可能感兴趣的:(Swift - LeetCode - 二叉树的层次遍历)