Topic:
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).
For example:
Given binary Tree [3,9,20,null,null,15,7] ,
3 / 9 / 7
Return its zigzag level order traversal as:
[ 3], [20,9], [15,7]]
test instructions and analysis: a cross-traverse two-fork tree is given, which requires the points of each layer to traverse horizontally according to the Z-shape. We can use stack to solve this problem, simply to add each layer to a stack, and then traverse the output of the node to add the child nodes to a new stack (first add the left child node or the right child node according to the order of the previous layer added), After traversing, the new stack is assigned to the stack for the next layer of traversal. The code is as follows :
Code:
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public list<list<integer>> zigzaglevelorder (TreeNode root) {list<list <Integer>> res=new arraylist<> (); TreeNode Node=root; stack<treenode> stack =new stack<> (); if (node!=null) stack.push (node); int leftorright=0;//0 is the first to traverse the left subtree, 1 is the right subtree while (!stack.isempty ()) {stack<treenode> nextstack =new stack<> (); List<integer> list=new arraylist<> (); while (!stack.isempty ()) {TreeNode temp=stack.pop (); List.add (temp.val); if (leftorright==0) {if (temp.left!=null) Nextstack.push (Temp.left); if (temp.right!=null) Nextstack.push (temp.right); }else{if (temp.right!=null) Nextstack.push (temp.right), if (temp.left!=null) Nextstack.push (Temp.left);}} if (leftorright==0) leftorright=1; else {leftorright=0;} res.add (New arraylist<> (list)); System.OUT.PRINTLN (list); List.clear (); stack= (stack<treenode>) Nextstack.clone (); Nextstack.clear (); } return res; }}
[Leetcode] 103. Binary Tree Zigzag level Order traversal Java