Leetcode Binary Tree Right Side View
题目链接:https://leetcode.com/problems/binary-tree-right-side-view/
递归法解法:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Solution { public List<Integer> rightSideView(TreeNode root) { Map<Integer,Integer> map = new HashMap<Integer,Integer>(); breadthFirstSearch(root,map,0); List<Integer> list = new LinkedList<Integer>(); for(Entry<Integer,Integer> entry:map.entrySet()){ list.add(entry.getKey(),entry.getValue()); } return list; } public void breadthFirstSearch(TreeNode root,Map<Integer,Integer> map,int depth){ if(root == null){ return; } if(!map.containsKey(depth)){ map.put(depth,root.val); } breadthFirstSearch(root.right,map,depth+1); breadthFirstSearch(root.left,map,depth+1); } }
遍历解法:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> list = new LinkedList<Integer>(); Queue<TreeNode> queue = new LinkedList<TreeNode>(); int count = 0; count++; if(root == null){ return list; } queue.offer(root); while(true){ int next = 0; while(count>0){ TreeNode tmp = queue.poll(); count--; if(count == 0){ list.add(tmp.val); } if(tmp.left != null){ queue.offer(tmp.left); next++; } if(tmp.right != null){ queue.offer(tmp.right); next++; } } if(next==0){ break; }else{ count = next; } } return list; } }

浙公网安备 33010602011771号