之前面试正好问道了这样一题,但菜的么有写出来,这里总结整理一下
思想:层序遍历
正好复习一下二叉树的层序遍历
层序遍历算法用的最多的实现方法就是引入一个辅助的顺序队列来进行保存,每次弹出队首元素即可
static Queue<TreeNode> nodelist = new LinkedList<>();
static void ceng(TreeNode root) {
TreeNode front = null;
if(root == null)
return;
nodelist.offer(root);
while(!nodelist.isEmpty()) {
front = nodelist.poll();
if(front.left != null)
nodelist.offer(front.left);
if(front.right != null)
nodelist.offer(front.right);
System.out.println(front.val);
}
}
但此处要实现左侧视角下的二叉树,其实就是每层的第一个元素,所以最先想到就应该是层序遍历(我当初咋就没相当咧.....),
public void leftView(){
TreeNode front = null;
nodelist.offer(mRoot);
int flag = 1;
TreeNode last = mRoot; //该层最后一个元素
TreeNode frontlast = mRoot; //上一层最后一个元素
while(!nodelist.isEmpty()){

这篇博客主要总结了如何解决编程面试中关于二叉树的左侧视角问题。通过层序遍历的方法,博主详细解释了如何获取每层的第一个元素,即左侧视角下的节点。层序遍历通常使用队列作为辅助数据结构,依次弹出队首元素来实现。
最低0.47元/天 解锁文章
1141

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



