leetCode :103. Binary Tree Zigzag Level Order Traversal (swift) 二叉树Z字形层次遍历

// 103. Binary Tree Zigzag Level Order Traversal

// https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/description/

// swift

// 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 zigzagLevelOrder(_ root: TreeNode?) -> [[Int]] {

        guard root != nil else {

            return [[Int]]()

        }

        func nextLevelResult(_ nodes: [TreeNode], flag: Bool) -> [TreeNode] {

            var result = [TreeNode]()

            for node in nodes.reversed() {

                if flag {

                    if (node.left != nil) {

                        result.append(node.left!)

                    }

                    if (node.right != nil) {

                        result.append(node.right!)

                    } 

                } else {

                    if (node.right != nil) {

                        result.append(node.right!)

                    }

                    if (node.left != nil) {

                        result.append(node.left!)

                    }

                }

            }

            return result

        }

        

        var result = [[TreeNode]]()

        var temp = [root!]

        var flag = false

        while temp.count > 0 {

            result .append(temp)

            temp = nextLevelResult(temp, flag: flag)

            flag = !flag

        }

        

        return result.map { nodes in

            nodes.map { node in

                node.val

            }

        }

    }

}

 

posted @ 2018-03-09 14:56  孔凡凯凯  阅读(163)  评论(0编辑  收藏  举报