广度优先搜索中等 leetcode199. 二叉树的右视图

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.ArrayList;
import java.util.LinkedList;
class Solution {
    /*
    和层次遍历一样的,只不过每次只保存队列的最后一个结点的值
    */
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        TreeNode cur = root;
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0;i < size;i++){
                TreeNode tmp = queue.poll();
                if(i == size-1){
                    res.add(tmp.val);
                }
                TreeNode l = tmp.left;
                TreeNode r = tmp.right;
                if(l != null){
                    queue.add(l);
                }
                if(r != null){
                    queue.add(r);
                }
            }
        }
        return res;
    }
}

你可能感兴趣的:(二叉树,队列,queue,leetcode)