Leetcode-103. Binary Tree Zigzag Level Order Traversal

来源:互联网 发布:乳业数据 编辑:程序博客网 时间:2024/06/06 13:03

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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]]

一开始以为还是用两个队列,只是插入的顺序不一样,后来仔细想想,原来是用堆。。Your runtime beats 10.01% of java submissions.

public class Solution {    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {        List<List<Integer>> results = new ArrayList<List<Integer>>();Stack<TreeNode> stack1 = new Stack<TreeNode>();Stack<TreeNode> stack2 = new Stack<TreeNode>();if(root != null){stack1.push(root);while(!stack1.empty()  || !stack2.empty()){if(!stack1.empty()){List<Integer> result = new ArrayList<Integer>();while(!stack1.empty()){TreeNode node = stack1.pop();result.add(node.val);if(node.left != null) stack2.push(node.left);if(node.right != null) stack2.push(node.right);}results.add(result);}if(!stack2.empty()){List<Integer> result = new ArrayList<Integer>();while(!stack2.empty()){TreeNode node = stack2.pop();result.add(node.val);if(node.right != null) stack1.push(node.right);if(node.left != null) stack1.push(node.left);}results.add(result);}}}return results;    }}





0 0