题目
给定一棵二叉树,想象自己站在它的右侧,返回从顶部到底部看到的节点值。
例如:
给定以下二叉树,
1 <--- / \ 2 3 <--- \ \ 5 4 <---
你应该返回 [1, 3, 4]
。
分析
首先把二叉树的根节点添加到list结果集合中,然后遍历二叉树,首先遍历它的右子树,当结果添加一个之后,给deep+1,代表当前的最右侧的数的深度。每遍历一层的时候都要先给temp+1,代表当前树的深度。
当temp<deep的时候,不符合题意,所以不添加入结果集,继续遍历,
当temp > deep 的时候,符合题意, 加入结果街。
还有temp = deep时,需要判断一下是不是最右边的树,如果是最右边的树则加入list,如果不是,则不加入。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
static boolean flag = true;//是否还存在最右边的树
static int deep = 0;
public List<Integer> rightSideView(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null)
return list;
list.add(root.val);
deep = 0;
flag = true;
iterator(root,list,0);
return list;
}
public static void iterator(TreeNode root, List<Integer>list, int temp){
temp++;
if (root.right != null){
if (temp >deep || (temp == deep && flag)){
list.add(root.right.val);
deep++;
}
iterator(root.right,list,temp);
}else
flag = false;//最右边遍历完毕,flag==false了之后 当temp==deep的时候 则不符合条件
if (root.left != null){
if (temp > deep || (temp == deep && flag)){
list.add(root.left.val);
deep++;
}
iterator(root.left,list,temp);
}
}
}