Skip to content

Latest commit

 

History

History
98 lines (84 loc) · 2.26 KB

20201028.md

File metadata and controls

98 lines (84 loc) · 2.26 KB

Algorithm

103. Binary Tree Zigzag Level Order Traversal

Description

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  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 /**
  * Definition for a binary tree node.
  * public class TreeNode {
  *     int val;
  *     TreeNode left;
  *     TreeNode right;
  *     TreeNode(int x) { val = x; }
  * }
  */
  class Solution {
     public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
         List<List<Integer>> listNode = new LinkedList<>();
         Stack<TreeNode> stack1 = new Stack<>();
         Stack<TreeNode> stack2 = new Stack<>();
         if(root == null){
             return listNode;
         }
         stack1.push(root);
         while(!stack1.isEmpty()||!stack2.isEmpty()){
             List<Integer> subList = new LinkedList<>();
             if(!stack1.isEmpty()){
                 while(!stack1.isEmpty()){
                     TreeNode node = stack1.pop();
                     if(node!=null){
                         subList.add(node.val);
                         stack2.push(node.left);
                         stack2.push(node.right);
                     }
                 }
             }else if(!stack2.isEmpty()){
                 while(!stack2.isEmpty()){
                     TreeNode node = stack2.pop();
                     if(node!=null){
                         subList.add(node.val);
                         stack1.push(node.right);
                         stack1.push(node.left);
                     }
                 }
             }
             if(!subList.isEmpty()){
                 listNode.add(subList);
             }
         }
         return  listNode;
     }
 }

Discuss

借助两个栈实现,注意出栈入栈的顺序

Review

Tip

Share