原题是说站在二叉树的右侧,从根到叶能看到的节点,也就是说同层右边的节点能挡住同层左边的节点。这个问题,基于层级遍历二叉树的基础来做即可,用代理模式新建一个类别包装TreeNode节点,添加属性level,根为0,孩子节点level+1, 然后判断是不是该层最后一个节点,可能没有办法,只能通过下一个节点层级是否与前一次不同,这样每次遍历实际上要记录前一次的level和value,代码如下:
import java.util.LinkedList;
class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
class TreeNodeWithLevel{
TreeNode tn;
int level;
public TreeNodeWithLevel(TreeNode tn) {
this.tn = tn;
}
public TreeNodeWithLevel(TreeNode tn, int level) {
this.tn = tn;
this.level = level;
}
}
public class Test {
public static void traverse(TreeNode root){
LinkedList<TreeNodeWithLevel> layer = new LinkedList<>();
layer.add(new TreeNodeWithLevel(root, 0));
int preLevel = -1;
int preValue = Integer.MAX_VALUE;
while(!layer.isEmpty()){
TreeNodeWithLevel cur = layer.poll();
if(cur.level!=preLevel && preLevel != -1){
System.out.println(preValue);
}
if(cur.tn.left!=null){
layer.offer(new TreeNodeWithLevel(cur.tn.left, cur.level+1));
}
if(cur.tn.right!=null){
layer.add(new TreeNodeWithLevel(cur.tn.right,cur.level+1));
}
preLevel = cur.level;
preValue = cur.tn.val;
}
System.out.println(preValue);
}
public static void main(String[] args){
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
// root.right.left = new TreeNode(6);
// root.right.right = new TreeNode(7);
traverse(root);
}
}