关于网页设计泰安网站seo推广
题目:
给定一个二叉树的 根节点 root
,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
方法(灵神):先递归右子树,再递归左子树,在递归的同时记录一个节点个数或者说递归深度,如果递归深度等于答案的长度,那么这个节点就需要记录到答案中,深度小于答案的长度不记录。
代码:
class Solution {private final List<Integer> ans = new ArrayList<>();public List<Integer> rightSideView(TreeNode root) {dfs(root,0);return ans;}private void dfs(TreeNode root, int depth) {if (root == null)return;if (depth == ans.size())ans.add(root.val);dfs(root.right, depth + 1);dfs(root.left, depth + 1);}
}