zoukankan      html  css  js  c++  java
  • 二叉树的锯齿形层次遍历 · Binary Tree Zigzag Level Order Traversal

    [抄题]:

    给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行) 

    [思维问题]:

    不知道反复切换要怎么做:用boolean normalOrder当作布尔型控制变量

    [一句话思路]:

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    root一个点正常出入。第二层先左后右,出来就变成先右后左了。

    [一刷]:

    1. 层遍历是放在原来的queue中,但是zigzag遍历的左右节点是放在下一层,另外一个栈next中。不要搞错
    2. 栈交换也是循环操作的,栈交换需要放在循环体里面

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

    [总结]:

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    用两个栈:可以实现逆序,来回交换

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

    层遍历

    public class Solution {
        /*
         * @param root: A Tree
         * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
         */
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            //define
            Stack<TreeNode> curt = new Stack<TreeNode>();
            Stack<TreeNode> next = new Stack<TreeNode>();
            Stack<TreeNode> temp = new Stack<TreeNode>();
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            boolean normalOrder = true;
            
            if (root == null) {
                return result;
            }
            
            //put into stack
            curt.push(root);
            while (!curt.isEmpty()) {
                List<Integer> level = new LinkedList<Integer>();
                int size = curt.size();
                for (int i = 0; i < size; i++) {
                    TreeNode node = curt.pop();
                    level.add(node.val);
                if (normalOrder == true) {
                    if (node.left != null) {
                        next.push(node.left);//
                    }
                    if (node.right != null) {
                        next.push(node.right);
                    }
                }
                else {
                    if (node.right != null) {
                        next.push(node.right);
                    }
                    if (node.left != null) {
                        next.push(node.left);
                    }
                }
                }
                result.add(level);
                //reverse stack
                temp = curt;
                curt = next;
                next = temp;
                normalOrder = !normalOrder;//
            }
            
            //output result
            return result;
        }
    }
    View Code
  • 相关阅读:
    windows和linux下安装 redis
    YII1 配置redis并使用
    YII1 安装smarty模版引擎
    thinkphp5 阿里云短信 发送多参数的短信
    利用securecrt或者xshell 下载服务器端文件到本地windows系统中
    Swift 内存管理
    扩展和协议
    继承
    构造与析构
    方法
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8387846.html
Copyright © 2011-2022 走看看