199. Binary Tree Right Side View
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].
分析:
这题有迷惑性,不要以为只是让你找出最右边的节点,如果左边节点比右边节点高,那么左边节点的右边部分也要输出来。
这题可以按层获取树的节点,然后把每层最右边的找出来。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<Integer> rightSideView(TreeNode root) { 12 List<Integer> result = new ArrayList<>(); 13 if (root == null) return result; 14 15 Queue<TreeNode> queue = new LinkedList<>(); 16 queue.offer(root); 17 18 while (!queue.isEmpty()) { 19 int size = queue.size(); 20 for (int i = 0; i < size; i++) { 21 TreeNode top = queue.poll(); 22 if (i == size - 1) { 23 result.add(top.val); 24 } 25 if (top.left != null) { 26 queue.add(top.left); 27 } 28 if (top.right != null) { 29 queue.add(top.right); 30 } 31 } 32 } 33 return result; 34 } 35 }
1 public class Solution { 2 // The core idea of this algorithm: 3 // 1.Each depth of the tree only select one node. 4 // 2. View depth is current size of result list. 5 public List<Integer> rightSideView(TreeNode root) { 6 List<Integer> result = new ArrayList<Integer>(); 7 rightView(root, result, 0); 8 return result; 9 } 10 11 public void rightView(TreeNode curr, List<Integer> result, int currDepth){ 12 if(curr == null) return; 13 if(currDepth == result.size()){ 14 result.add(curr.val); 15 } 16 rightView(curr.right, result, currDepth + 1); 17 rightView(curr.left, result, currDepth + 1); 18 } 19 }

浙公网安备 33010602011771号