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
  • 相关阅读:
    xcode 常用插件 加快开发速度 --严焕培
    iOS,蓝牙开发!!--By帮雷
    获取加速度数据,陀螺仪数据,磁场数据的两种方式-陈鹏
    简单仿京东"筛选"界面 双导航栏控制器共存 by Nicky.Tsui
    扩展NSDate类实现快捷使用 —— 昉
    如何实现视图圆角效果的三种方法及比较——董鑫
    无意进去UIView随笔闹腾着玩 -by 胡 xu
    简单实现UITableView索引功能(中英文首字母索引)(一) ByH罗
    动画推荐-By胡罗
    [手游项目3]-20-golang向上取整、向下取整和四舍五入
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8387846.html
Copyright © 2011-2022 走看看