标签:
第一个是BFS
public class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<Integer>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); result.add(queue.peek().val); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); if (node.right != null) { queue.offer(node.right); } if (node.left != null) { queue.offer(node.left); } } } return result; } }
这是DFS的解法
public class Solution { List<Integer> result = new ArrayList<Integer>(); public List<Integer> rightSideView(TreeNode root) { dfs(root, 1); return result; } public void dfs(TreeNode root, int level) { if (root == null) { return; } if (result.size() < level) { result.add(root.val); } dfs(root.right, level + 1); dfs(root.left, level + 1); } }
[LeetCode]Binary Tree Right Side View
标签:
原文地址:http://www.cnblogs.com/vision-love-programming/p/5004665.html