Skip to content

103. Binary Tree Zigzag Level Order Traversal

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

js
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
function zigzagLevelOrder(root) {
  if (!root) {
    return []
  }

  const result = []
  let current = [root]
  let ltr = true

  while (current.length) {
    const vals = []
    const next = []

    for (let i = current.length - 1; i >= 0; i--) {
      const node = current[i]
      vals.push(node.val)
      if (ltr) {
        if (node.left) {
          next.push(node.left)
        }
        if (node.right) {
          next.push(node.right)
        }
      } else {
        if (node.right) {
          next.push(node.right)
        }
        if (node.left) {
          next.push(node.left)
        }
      }
    }

    ltr = !ltr
    result.push(vals)
    current = next
  }

  return result
}
py
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution(object):

    def zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        current, result = [root], []
        ltr = True
        while current:
            vals, nxt = [], []
            for node in reversed(current):
                vals.append(node.val)
                if ltr:
                    if node.left:
                        nxt.append(node.left)
                    if node.right:
                        nxt.append(node.right)
                else:
                    if node.right:
                        nxt.append(node.right)
                    if node.left:
                        nxt.append(node.left)
            ltr = not ltr
            result.append(vals)
            current = nxt
        return result
go
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func zigzagLevelOrder(root *TreeNode) [][]int {
	if root == nil {
		return [][]int{}
	}

	var result [][]int
	current := []*TreeNode{root}
	ltr := true

	for len(current) > 0 {
		var vals []int
		var next []*TreeNode

		for i := len(current)-1; i >= 0; i--{
			node := current[i]
			vals = append(vals, node.Val)
			if ltr {
				if node.Left != nil {
					next = append(next, node.Left)
				}
				if node.Right != nil {
					next = append(next, node.Right)
				}
			} else {
				if node.Right != nil {
					next = append(next, node.Right)
				}
				if node.Left != nil {
					next = append(next, node.Left)
				}
			}
		}

		ltr = !ltr
		result = append(result, vals)
		current = next
	}

	return result
}