zoukankan      html  css  js  c++  java
  • NC15 求二叉树的层序遍历

    package NC;

    import java.util.*;

    /**
    * NC15 求二叉树的层序遍历
    *
    * 给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
    * 例如:
    * 给定的二叉树是{3,9,20,#,#,15,7},
    *
    * @author Tang
    * @date 2021/9/27
    */
    public class LevelOrder {

    Map<Integer, ArrayList<Integer>> tempMap = new HashMap<>();


    public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
    // write code here
    postSearch(root, 0);

    ArrayList<ArrayList<Integer>> resultList = new ArrayList<>();
    for(int i = 0; i < tempMap.size(); i++) {
    ArrayList<Integer> list = tempMap.get(i);
    resultList.add(list);
    }

    return resultList;

    }

    /**
    * 后序遍历
    */
    private void postSearch(TreeNode node, int ceng) {
    if(node == null) {
    return;
    }

    postSearch(node.left, ceng+1);
    postSearch(node.right, ceng+1);


    //在特定层数的arrayList添加
    if(tempMap.get(ceng) == null) {
    ArrayList<Integer> arrayList = new ArrayList<>();
    tempMap.put(ceng, arrayList);
    }
    tempMap.get(ceng).add(node.val);

    }

    public static void main(String[] args) {

    TreeNode treeNode1 = new TreeNode(3);
    TreeNode treeNode2 = new TreeNode(9);
    TreeNode treeNode3 = new TreeNode(20);
    TreeNode treeNode4 = new TreeNode(15);
    TreeNode treeNode5 = new TreeNode(7);
    treeNode1.left = treeNode2;
    treeNode1.right = treeNode3;
    treeNode3.left = treeNode4;
    treeNode3.right = treeNode5;

    ArrayList<ArrayList<Integer>> arrayLists = new LevelOrder().levelOrder(treeNode1);




    }

    }


    class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
    this.val = val;
    }
    }
  • 相关阅读:
    优达,计算机科学导论
    关于未来发展阶段小结
    CS50.5
    CS50.4
    简单查看tomcat中部署java服务的内存使用情况
    python3环境搭建(CentOS7.2)
    mysql主从配置脚本
    安装rkhunter
    转移到博客园啦!
    Eclipse上Maven环境配置使用 (全)
  • 原文地址:https://www.cnblogs.com/ttaall/p/15342584.html
Copyright © 2011-2022 走看看