Given a binary tree, imagine yourself standing on the right side of it,
return the values of the nodes you can see ordered from top to bottom. For example: Given the following binary tree, 1 <--- / 2 3 <--- 5 4 <--- You should return [1, 3, 4]. Credits: Special thanks to @amrsaqr for adding this problem and creating all test cases.
算法: 根右左, 尾递归
容器: list 尾递归
corner case: 右没有怎么办, 加一个输入值表示深度, list.size() 也表示深度
The core idea of this algorithm:
1.Each depth of the tree only select one node.
2.View depth is current size of result list.
public List<Integer> rightSideView(TreeNode root) { List<Integer> ans = new ArrayList<Integer>(); if (root == null) { return ans; } helper(root, ans, 0); return ans; } private void helper(TreeNode root, List<Integer> ans, int size) { if (root == null) { return; } if (size == ans.size()) { ans.add(root.val); } helper(root.right, ans, size + 1); helper(root.left, ans, size + 1); }
是递的时候操作题意还是归的时候操作? --->尾递归? 输入值? 还是分治? , 辅助全局变量?