199.二叉树的右视图
思路:
使用根->右->左方法进行遍历节点,同时记录层数,将当前层数与记录的层数进行比较,如果当前层数大于记录的层数,添加该元素,若当前层数小于记录的层数,说明该层已经有元素被记录,就跳过,这样保证每层第一个被记录的一定是最右边的元素
java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int maxHigh = 0;
List<Integer> res = new ArrayList<Integer>();
public List<Integer> rightSideView(TreeNode root) {
dfs(root,1);
return res;
}
public void dfs(TreeNode root,int high){
if(root == null){
return ;
}
if(maxHigh < high){
res.add(root.val);
maxHigh = high;
}
dfs(root.right,high + 1);
dfs(root.left,high + 1);
}
}