LeetCode:103Binary Tree Zigzag Level Order Traversal

真是不容易啊,做这道题的时候脑子一团乱,感觉还是得劳逸结合啊。这道题的思想不难,就是宽搜BFS。通过设置一个flag来判断是否需要逆序输出。

我的做法虽然AC,但是觉得代码还是不好,空间占用较多。

 /**
 * 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>> result = new ArrayList< >();
        Queue<TreeNode> queue = new LinkedList<>();

        if(root == null)
        {
            return result;
        }
        queue.add(root);
        boolean flag = true;
        while (!queue.isEmpty())
        {
            int i=0;
            List<Integer> tempList = new ArrayList<>();
            int count = queue.size();
            while (i<count) {
                TreeNode Node = queue.poll();
                tempList.add(Node.val);
                    if (Node.left != null) {
                        queue.add(Node.left);
                    }
                    if (Node.right != null) {
                        queue.add(Node.right);
                    }
                i++;
            }
            if(flag==false)
            {
                Stack<Integer> tempstack = new Stack<>();
                for (Integer tem: tempList
                     ) {
                    tempstack.push(tem);
                }
                List<Integer> list2 = new ArrayList<>();
                while (!tempstack.isEmpty())
                {
                    list2.add(tempstack.pop());
                }
                result.add(list2);

            }
            else
            {
                result.add(tempList);
            }
            flag=!flag;
        }
       return result;
    }
}

 

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