问题描述
打印从左往右看到的二叉树(就是打印每层第一个节点)
二叉树的左(右)视图即:以从上到下的顺序,输出一颗二叉树每一层最左(右)端的节点,结果就是其左(右)视图。
如下图,左视图为 6,5,0,3

public static List<String> solution(Node node){
if(null == node){
return Collections.emptyList();
}
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
pre(node, map, 1);
List<String> result = new ArrayList<String>();
for(Integer key : map.keySet()){
result.add(map.get(key));
}
return result;
}
public static void pre(Node node, TreeMap<Integer,String> map, int level){
if(null == node){
return;
}
if(!map.containsKey(level)){
map.put(level, node.data);
}
pre(node.lc, map, level + 1);
pre(node.rc, map, level + 1);
}
本文介绍了一种算法,用于打印二叉树的左视图或右视图,即从上到下输出每一层最左或最右端的节点。通过使用TreeMap进行层级记录,确保了节点按正确顺序输出。
4712

被折叠的 条评论
为什么被折叠?



