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<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;
    }
}

官方解

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值