zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    数据结构之静态库动态库
    数据结构之二叉树
    数据结构之学习大纲
    Unix高级编程之文件及目录
    Unix高级编程之标准IO
    Unix高级编程之文件IO
    Unix高级编程之进程控制
    Unix高级编程之进程环境
    内置支持类(RegExp)
    获取DOM元素的三种方法
  • 原文地址:https://www.cnblogs.com/ren-jie/p/5273867.html
Copyright © 2011-2022 走看看