IncredibleThings

导航

LeetCode - 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.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public  List<Integer> rightSideView(TreeNode root) {
    	List<Integer> res = new ArrayList<Integer>();
    	if(root == null){
    		return res;
    	}
    	Queue<TreeNode> queue = new LinkedList<>();
    	
    	queue.add(root);
    	while(true){
    		Queue<TreeNode> temp = new LinkedList<>();
	    	while(!queue.isEmpty()){
	    		TreeNode node  = queue.poll();
	    		if(queue.size() == 0){
	    			res.add(node.val);
	    		}
	    		if(node.left != null){
	    			temp.add(node.left);
	    		}
	    		if(node.right != null){
	    			temp.add(node.right);
	    		}
	    	}
	    	if(temp.isEmpty()){
	    		return res;
	    	}
	    	queue = temp;
    	}
    }
    
}

  

posted on 2018-10-16 05:21  IncredibleThings  阅读(82)  评论(0编辑  收藏  举报