上善若水 大盈若冲
LeetCode link
solution1
1234567891011121314151617181920212223
public class Solution { public List<Integer> rightSideView(TreeNode root) { ArrayList<Integer> result = new ArrayList<>(); this.rightSideView(root, 0, result); return result; } private void rightSideView(TreeNode node, int level, ArrayList<Integer> result) { if (node == null) { return; } if (result.size() <= level) { result.add(node.val); this.rightSideView(node.left, level + 1, result); this.rightSideView(node.right, level + 1, result); } else { result.set(level, node.val); this.rightSideView(node.left, level + 1, result); this.rightSideView(node.right, level + 1, result); } }}
solution2
BFS
1234567891011121314151617181920212223242526
class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { Queue<TreeNode> queue2 = new LinkedList<>(); TreeNode lastNode = queue.peek(); while (!queue.isEmpty()) { lastNode = queue.poll(); if (lastNode.left != null) { queue2.add(lastNode.left); } if (lastNode.right != null) { queue2.add(lastNode.right); } } result.add(lastNode.val); queue = queue2; } return result; }}