二叉树的锯齿形层次遍历

flag

软件学院大三党,每天一道算法题,第十八天

题目介绍

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

思路

迭代:采用经过加工的广度遍历,引入depth层数,逐层将元素放入链表(奇数层插入到尾部,偶数层插入到头部),用队列的长度代表每层的元素个数,即内层循环的次数,再将下一层元素放入队列。

递归:类似深度优先遍历

关键代码
迭代

public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {

    List<List<Integer>> lists=new ArrayList<>();
    if(root==null)
        return lists;
    Queue<TreeNode>queue=new LinkedList<>();
    queue.add(root);
    int depth=0;
    while (!queue.isEmpty()){
        List<Integer> tmp = new LinkedList<>();
        int count=queue.size();
        for(int i=0;i<count;i++){
            TreeNode temp=queue.poll();
            if(depth%2==0)
                tmp.add(temp.val);
            else//从首部添加元素
                tmp.add(0,temp.val);
            if(temp.left!=null)
                queue.add(temp.left);
            if(temp.right!=null)
                queue.add(temp.right);
        }
        lists.add(tmp);
        depth++;

    }
    return lists;

}

递归

public static List<List<Integer>> zigzagLevelOrder2(TreeNode root) {
    List<List<Integer>> res = new ArrayList<>();
    helper(res, root, 0);
    return res;

}

public static void helper(List<List<Integer>> lists, TreeNode root, int depth) {
    if (root == null)
        return;
    if (lists.size() == depth)
        lists.add(new LinkedList<>());
    if (depth % 2 == 0)
        lists.get(depth).add(root.val);
    else 
        lists.get(depth).add(0, root.val);
    helper(lists, root.left, depth + 1);
    helper(lists, root.right, depth + 1);
}

测试

TreeNode test=new TreeNode(1);
test.left=new TreeNode(2);
test.left.right=new TreeNode(4);
test.right=new TreeNode(9);
test.right.left=new TreeNode(4);
test.right.right=new TreeNode(3);
List<List<Integer>>l=zigzagLevelOrder(test);
for(int i=0;i<l.size();i++)
    System.out.println(l.get(i));

结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值