之前面试正好问道了这样一题,但菜的么有写出来,这里总结整理一下
思想:层序遍历
正好复习一下二叉树的层序遍历
层序遍历算法用的最多的实现方法就是引入一个辅助的顺序队列来进行保存,每次弹出队首元素即可
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()){
front = nodelist.poll();
if(flag == 1){
System.out.println(front.value);
flag = 0;
}
if(front.leftNode != null){
nodelist.offer(front.leftNode);
last = front.leftNode;
}
if (front.rightNode != null){
nodelist.offer(front.rightNode);
last = front.rightNode;
}
if(frontlast == front){
flag = 1;
frontlast = last;
}
}