二叉树的右视图
https://leetcode.cn/problems/binary-tree-right-side-view/description/?envType=study-plan-v2&envId=top-100-liked
题目
思路
考虑遍历的顺序,没当第一次遍历到每一层的最右边结点时,将该结点的值加入到列表
保证先遍历到每一层的最右边结点:修改二叉树的遍历顺序 跟 --- 右 --- 左
保证第二层的 3 加入返回list ,而不是 2 也加入:设置递归深度 depth ,每当第一次递归到 第二层时,将结点加入到 list,第二次递归到第二层时,不加入
总结:
使用 跟 --- 右 --- 左的递归顺序,方便第一层遍历到第二层时,将结点 3 加入到返回列表 list,然后修改是第一次遍历到该层的状态(用一个变量 记录 已经递归的最大深度)
代码
class Solution { private List<Integer> ans = new ArrayList<>(); private int max = -1; public List<Integer> rightSideView(TreeNode root) { //中 右 左 递归什么看有没有挡住 dfs(root, 0); return ans; } private void dfs(TreeNode root , int depth){ if(root == null) return; if(depth > max){ ans.add(root.val); } int nextDepth = depth + 1; max = Math.max(max , depth); dfs(root.right , nextDepth); dfs(root.left , nextDepth); } }