zoukankan      html  css  js  c++  java
  • 103. 二叉树的锯齿形层次遍历-中等难度

    问题描述

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

    例如:
    给定二叉树 [3,9,20,null,null,15,7],

    3
    /
    9 20
    /
    15 7
    返回锯齿形层次遍历如下:

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal

    解答

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
     /*
    dfs遍历二叉树,从左至右。每个元素都有个deep(深度),只需将root.val放入result.get(deep)数组中即可。
    时间复杂度O(n),击败97%用户。
     */
    class Solution {
        public static List<List<Integer>> result;
        public static void dfs(TreeNode root,int deep){
            if(root.left == null && root.right == null)return;
            if(root.left!=null){
                if(deep+1 > (result.size())-1)result.add(new LinkedList<Integer>());
                if(deep%2!=0)result.get(deep+1).add(root.left.val);
                else result.get(deep+1).add(0,root.left.val);
                dfs(root.left,deep+1);
            }
            if(root.right!=null){
                if(deep+1 > (result.size())-1)result.add(new LinkedList<Integer>());
                if(deep%2!=0)result.get(deep+1).add(root.right.val);
                else result.get(deep+1).add(0,root.right.val);
                dfs(root.right,deep+1);
            }
        }
        public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
            result = new ArrayList<List<Integer>>();
            if(root == null)return result;
            result.add(new LinkedList<Integer>());
            result.get(0).add(root.val);
            dfs(root,0);
            return result;
        }
    }
  • 相关阅读:
    爬虫之移动端数据爬取
    Python网络爬虫之图片懒加载技术、selenium和PhantomJS
    iOS-类方法
    iOS-二进制,十进制,十六进制的相互转换
    iOS-category
    iOS-.h和.m文件
    iOS-关于@property和@synthesize
    自定义控件-使用frame和代码的自定义UI控件
    跨平台开发
    GitHub探索
  • 原文地址:https://www.cnblogs.com/xxxxxiaochuan/p/13285298.html
Copyright © 2011-2022 走看看