zoukankan      html  css  js  c++  java
  • leetcode--103. Binary Tree Zigzag Level Order Traversal

    1、问题描述

    Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

    For example:
    Given binary tree [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7

    return its zigzag level order traversal as:

    [
      [3],
      [20,9],
      [15,7]
    ]

    2、边界条件:root == null

    3、思路:广度优先遍历BFS,只不过遍历过程中会变换一下顺序,用stack实现。双stack实现倒序。这是改变遍历的顺序。

    还有一种思路是改变保存结果的顺序。

    4、代码实现

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            List<List<Integer>> results = new ArrayList<>();
            if (root == null) {
                return results;
            }
            Stack<TreeNode> stack1 = new Stack<>();
            stack1.push(root);
            int ctrl = 0;
            int curLevelNum = 1;
            while (!stack1.isEmpty()) {
                List<Integer> result = new ArrayList<>();
                Stack<TreeNode> stack2 = new Stack<>();
                int nextLevelNum = 0;
                while (curLevelNum-- > 0) {
                    TreeNode top = stack1.pop();
                    result.add(top.val);
                    if (ctrl % 2 == 0) {
                        if (top.left != null) {
                            stack2.push(top.left);
                            nextLevelNum++;
                        }
                        if (top.right != null) {
                            stack2.push(top.right);
                            nextLevelNum++;
                        }
                    } else {
                        if (top.right != null) {
                            stack2.push(top.right);
                            nextLevelNum++;
                        }
                        if (top.left != null) {
                            stack2.push(top.left);
                            nextLevelNum++;
                        }
                    }
                }
                ctrl++;
                curLevelNum = nextLevelNum;
                stack1 = stack2;
                results.add(result);
            }
            return results;
        }
    }

    5、api

  • 相关阅读:
    PHP实现最简单爬虫原型
    xcache 安装与配置
    fckeditor[php]上传文章内容图片插件[提供技术支持]
    使用PHP创建一个REST API(Create a REST API with PHP)
    php错误处理
    PHP二维数组排序
    鼠标指针经过时整行变色的表格
    java net unicode / native2ascii / url decode / url encode / UTF8 / js url code
    java protocol / patent
    framework junit
  • 原文地址:https://www.cnblogs.com/shihuvini/p/7461288.html
Copyright © 2011-2022 走看看