• NC_15_levelOrder


    package org.example.interview.practice;
    
    import com.sun.jmx.remote.internal.ArrayQueue;
    
    import java.util.ArrayDeque;
    import java.util.ArrayList;
    import java.util.Objects;
    import java.util.Queue;
    
    /**
     * @author xianzhe.ma
     * @date 2021/8/21
     */
    
    public class NC_15_levelOrder {
    
        public static ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
            // write code here
            if (Objects.isNull(root)) {
                return new ArrayList<>();
            }
            ArrayList<ArrayList<Integer>> retList = new ArrayList<>();
    
            Queue<TreeNode> queue = new ArrayDeque<>();
            queue.add(root);
            while (!queue.isEmpty()) {
    
                ArrayList<TreeNode> levelList = new ArrayList<>();
                ArrayList<Integer> tempList = new ArrayList<>();
    
                while (!queue.isEmpty()) {
    
                    TreeNode node = queue.poll();
                    tempList.add(node.val);
                    levelList.add(node);
                }
    
                for (TreeNode node : levelList) {
                    if (Objects.nonNull(node.left)) {
                        queue.add(node.left);
                    }
                    if (Objects.nonNull(node.right)) {
                        queue.add(node.right);
                    }
                }
                levelList = null;
                retList.add(tempList);
            }
    
            return retList;
    
        }
    
        public static class TreeNode {
            int val = 0;
            TreeNode left = null;
            TreeNode right = null;
    
            public TreeNode(int val) {
                this.val = val;
            }
        }
    
        public static void main(String[] args) {
            TreeNode node0 = new TreeNode(1);
    //        TreeNode node1 = new TreeNode(1);
    //        TreeNode node2 = new TreeNode(2);
    //        node0.right = node1;
    //        node0.left = node2;
    //        int result = sumNumbers(node0);
    //        System.out.println(result);
            levelOrder(node0);
        }
    }
  • 相关阅读:
    鸟哥linux——分区命令:split
    鸟哥linux——管线命令
    鸟哥linux——命令执行的判断依据:;,&&,||
    linux:数据流重导向
    Tensorflow计算模型——计算图
    DNS域名解析与本机Host
    相似图片搜索的原理
    谈谈回文子串
    关于字符串精确匹配
    音频采样
  • 原文地址:https://www.cnblogs.com/juniorMa/p/15879439.html
Copyright © 2020-2023  润新知