[LeetCode|[LeetCode 103] Zigzag Traversal (medium)

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
【[LeetCode|[LeetCode 103] Zigzag Traversal (medium)】For example:

Given binary tree [3,9,20,null,null,15,7], 3 / \ 920 /\ 157 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ]

Solution
  • 关于Tree 和 Level,用BFS, 思路与102类似,用2个queuestack
  • 但是题目要求的是 zigzag level order, 先入后出,所以这里需要用stack.
  • 而且,如果假设TREE只有一个根节点时,其层数为1。
    ---- 偶数层,在向stack2加入新节点时,先add rightadd left.
    ---- 奇数层,在向stack2加入新节点时,先add leftadd right.
/** * Definition for a binary tree node. * public class TreeNode { *int val; *TreeNode left; *TreeNode right; *TreeNode(int x) { val = x; } * } */ class Solution { public List> zigzagLevelOrder(TreeNode root) { List> result = new ArrayList<> (); if (root == null) { return result; }Stack tracker1 = new Stack<> (); Stack tracker2 = new Stack<> (); int layer = 1; List subArray = new ArrayList<> (); tracker1.add (root); while (!tracker1.isEmpty ()) { TreeNode current = tracker1.pop (); subArray.add (current.val); if (layer % 2 != 0) { if (current.left != null) { tracker2.push (current.left); } if (current.right != null) { tracker2.push (current.right); } } else if (layer % 2 == 0) { if (current.right != null) { tracker2.push (current.right); }if (current.left != null) { tracker2.push (current.left); } }if (tracker1.isEmpty ()) { result.add (subArray); subArray = new ArrayList (); tracker1 = tracker2; tracker2 = new Stack (); layer++; }}return result; } }

    推荐阅读