zl程序教程

您现在的位置是:首页 >  Java

当前栏目

二叉树的右视图(力扣 199)Java广度优先遍历

2023-03-14 22:54:54 时间

一、题目描述



给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。


示例 1:

输入: [1,2,3,null,5,null,4]

输出: [1,3,4]


示例 2:

输入: [1,null,3]

输出: [1,3]


示例 3:

输入: []

输出: []


提示:

二叉树的节点个数的范围是 [0,100]

-100 <= Node.val <= 100 


二、思路讲解



 按层遍历二叉树,将每层最后一个节点的值添加进列表中。返回列表即可。

       

按层遍历二叉树的代码参考我之前的博客:二叉树的层序遍历 Java广度优先搜索

         

三、Java代码实现 



/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
 
        List<Integer> list = new ArrayList<>();
        if(root==null){
            return list;
        }
 
        LinkedList<TreeNode> queue = new LinkedList<>();        
        queue.add(root);
        while(!queue.isEmpty()){    //按层遍历二叉树
            int n = queue.size();  
            TreeNode node = null;          
            for(int i=0; i<n; i++){
                node = queue.poll();
                if(node.left!=null){
                    queue.add(node.left);
                }
                if(node.right!=null){
                    queue.add(node.right);
                }
            }
            if(node!=null){ //把每一层末尾的节点值放到list中
                list.add(node.val);
            }
        }
        return list;
    }
}



四、时空复杂度分析 


       

时间复杂度:        O(N)         

       

空间复杂度:        O(N)