LeetCode.103 Binary Tree Zigzag Level Order Traversal

来源:互联网 发布:雪梨淘宝店衣服质量 编辑:程序博客网 时间:2024/06/03 21:13

题目:

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]]
分析:

/** * 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) {         //给定二叉树,类似层序遍历(从左到右,然后从右到左,每层之间交替进行)        //思路:采用类似层序遍历方式,利用两个stack存储每次遍历完的节点。分别控制奇偶层的不同放入节点        List<List<Integer>> list = new ArrayList<>();        if (root == null) return list;        Stack<TreeNode> stackOdd = new Stack<TreeNode>();        Stack<TreeNode> stackEven = new Stack<TreeNode>();        //用来计数的标识位        int count = 1;        stackOdd.push(root);        while (!stackOdd.empty()||!stackEven.empty()) {            TreeNode temp;            List<Integer> subList = new ArrayList<Integer>();            while (count % 2 == 1 && !stackOdd.empty()) {                //取出父亲节点,将其对应的左和右孩子放入stackEven                temp = stackOdd.pop();                subList.add(temp.val);                if (temp.left != null)                    stackEven.add(temp.left);                if (temp.right != null)                    stackEven.add(temp.right);            }            while (count % 2 == 0 && !stackEven.empty()) {                //将偶数层的节点对应取出,放入stackOdd                temp = stackEven.pop();                subList.add(temp.val);                if (temp.right != null)                    stackOdd.add(temp.right);                if (temp.left != null)                    stackOdd.add(temp.left);            }            list.add(subList);            count++;        }        return list;    }}