Day53 二叉树的锯齿形层序遍历

102 阅读1分钟

给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)

leetcode-cn.com/problems/bi…

示例1:

给定二叉树 [3,9,20,null,null,15,7],

​ 3 /
9 20 /
15 7 返回锯齿形层序遍历如下:

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

Java解法

思路:

  • 昨天用栈实现时就导致了这种现象
  • 放入取出再放入正好带来了这种效果
package sj.shimmer.algorithm.m3_2021;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import sj.shimmer.algorithm.TreeNode;

/**
 * Created by SJ on 2021/3/19.
 */

class D53 {
    public static void main(String[] args) {
        System.out.println(zigzagLevelOrder(TreeNode.getInstance(new Integer[]{3, 9, 20, null, null, 15, 7})));
        System.out.println(zigzagLevelOrder(TreeNode.getInstance(new Integer[]{1,2,3,4,5})));

    }
    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> results = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root != null) {
            stack.add(root);
        }
        boolean toRight = true;
        while (!stack.isEmpty()){
            List<Integer> tempList = new ArrayList<>();
            Stack<TreeNode> temp = new Stack<>();
            while (!stack.isEmpty()) {
                TreeNode pop = stack.pop();
                if (pop != null) {
                    tempList.add(pop.val);
                    if (toRight) {
                        temp.add(pop.left);
                        temp.add(pop.right);
                    }else {
                        temp.add(pop.right);
                        temp.add(pop.left);
                    }
                }
            }
            toRight=!toRight;
            if (tempList.size()!=0) {
                results.add(tempList);
                stack = temp;
            }
        }
        return results;
    }
}

官方解

leetcode-cn.com/problems/bi…

  1. 广度优先遍历

    使用队列处理,大致逻辑差不多

    • 时间复杂度:O(N)

    • 空间复杂度:O(N)