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

  • 相关阅读:
    linux下将一个大的文件拆分成若干小文件
    linux远程下载文件 的两种方法之 ftp命令和scp命令
    Python正则表达式的七个使用范例
    isinstance()和type()
    “可变的”tuple
    Tomcat常用面试题
    Tomcat常用配置详解
    Java工程师该如何编写高效代码?
    收集100条实用的网络知识
    MySQL 19个规则数据库设计总结
  • 原文地址:https://www.cnblogs.com/shihuvini/p/7461288.html
Copyright © 2011-2022 走看看