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;
}
}
posted @ 2021-09-27 13:45  六小扛把子  阅读(32)  评论(0编辑  收藏  举报