LeetCode 103. Binary Tree Zigzag Level Order Traversal

本文介绍了一种二叉树的锯齿形层序遍历算法,通过广度优先搜索(BFS)的方式实现,针对不同层级采用从左到右或从右到左的遍历方式。该算法的时间复杂度为O(n),空间复杂度也为O(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里:https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

题目:

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]
]

题解:

这道题是BFS的变形,与Binary Tree Level Order Traversal相似。但是要求偶数行从左到右,奇数行从右到左。

其实还是BFS, 只不过需要添加一个flag来表明是否需要reverse, 这里用boolean reverse 表示.

Time Complexity: O(n).

Space: O(n). que最多有n/2个节点。

AC Java:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
12         List<List<Integer>> res = new ArrayList<List<Integer>>();
13         if(root == null){
14             return res;
15         }
16         
17         LinkedList<TreeNode> que = new LinkedList<TreeNode>();
18         que.add(root);
19         int curCount = 1;
20         int nextCount = 0;
21         List<Integer> item = new ArrayList<Integer>();
22         boolean reverse = false;
23         
24         while(!que.isEmpty()){
25             TreeNode tn = que.poll();
26             curCount--;
27             if(reverse){
28                 item.add(0, tn.val);
29             }else{
30                 item.add(tn.val);
31             }
32             
33             
34             if(tn.left != null){
35                 que.add(tn.left);
36                 nextCount++;
37             }
38             if(tn.right != null){
39                 que.add(tn.right);
40                 nextCount++;
41             }
42             if(curCount == 0){
43                 reverse = reverse ? false : true;
44                 
45                 res.add(new ArrayList<Integer>(item));
46                 item = new ArrayList<Integer>();
47                 curCount = nextCount;
48                 nextCount = 0;
49             }
50         }
51         return res;
52     }
53 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4825020.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值