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

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

https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/

示例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> zigzagLevelOrder(TreeNode root) {
        List> results = new ArrayList<>();
        Stack stack = new Stack<>();
        if (root != null) {
            stack.add(root);
        }
        boolean toRight = true;
        while (!stack.isEmpty()){
            List tempList = new ArrayList<>();
            Stack 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;
    }
}
image

官方解

https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/solution/er-cha-shu-de-ju-chi-xing-ceng-xu-bian-l-qsun/

  1. 广度优先遍历

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

    • 时间复杂度:O(N)

    • 空间复杂度:O(N)

你可能感兴趣的:(Day53 二叉树的锯齿形层序遍历)