[leet code] Binary Tree Zigzag Level Order Traversal

本博客介绍了一种二叉树zigzag level order遍历的方法,通过控制添加节点的顺序来实现从左到右或从右到左的交替遍历。详细解释了两种实现思路,并提供了解决方案。

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

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,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

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

================

Idea is base on the binary tree level order transverse.  The change for this problem is that when we are adding node for level%2 ==0, we need to add node from left to right.  Otherwise, we need to add node from right to left.

To implement this change, I firstly try to reverse the adding order by changing the order of recursive call, i.e. when current level%2 == 0, process its right child then left child.  However, the result turned out that it's wrong.  for example, in the case of {3,9,20,1,2,15,7} the output of 2nd level would be [15,7,1,2], while we are expecting [1,2,15,7].  In another word, this approach can only "partially" implement the order reverse.

Another way of reversing the order is when we are constructing the array list for current level, we can choose to add at the beginning of the array list, or in at the end of the array list.  In this case, we always process child nodes from left to right, we control the order of the all nodes in specific level by controlling the adding position (at the beginning or at the end).

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> rs = new ArrayList<ArrayList<Integer>>();
        if(root == null) return rs;
        helper(root, 0, rs);
        return rs;
    }
    
    public void helper(TreeNode node, int depth, ArrayList<ArrayList<Integer>> rs){
        if(node == null) return;
        
        ArrayList<Integer> currLevel = null;
        if(rs.size()<depth+1){
            currLevel = new ArrayList<Integer>();
            rs.add(currLevel);
        }
        else currLevel=rs.get(depth);
        
        if(depth%2==0) currLevel.add(node.val);// newly added for this problem
        else currLevel.add(0, node.val);// newly added for this problem
        
        helper(node.left, depth+1, rs);
        helper(node.right, depth+1, rs);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值