leetcode Binary Tree Zigzag Level Order Traversal

题目链接

思路:
简单思路

/** * 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) {




        LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
        Stack<Integer> stack=new Stack<Integer>();
        LinkedList<List<Integer>> result=new LinkedList<List<Integer>>();
        LinkedList<Integer> row=new LinkedList<Integer>();
        boolean useStack=false;
        if(root==null)
        {
            return result;
        }

        queue.add(root);
        queue.add(null);

        while(queue.size()>0)
        {
            TreeNode temp=queue.pop();
            if(temp==null)
            {
                if(useStack)
                {

                    while(!stack.empty())
                    {
                        row.add(stack.pop());
                    }
                }
                result.add(row);
                row=new LinkedList<Integer>();
                useStack=!useStack;
                if(queue.size()>0)
                {
                    queue.add(null);
                    continue;
                }
                else
                {
                    break;
                }
            }   

            if(useStack)
            {
                stack.add(temp.val);
            }
            else
            {
                row.add(temp.val);
            }
            if(temp.left!=null)
            {
                queue.add(temp.left);
            }
            if(temp.right!=null)
            {
                queue.add(temp.right);
            }
        }
        return result;
    }
}

你可能感兴趣的:(leetcode Binary Tree Zigzag Level Order Traversal)