二叉树的右视图 (Binary Tree Right Side View)

 

思路:

// @Title: 二叉树的右视图 (Binary Tree Right Side View)
// @Author: qisiii
// @Date: 2024-09-14 23:27:09
// @Runtime: 1 ms
// @Memory: 40.8 MB
// @comment: 
// @flag: 
/**
 * 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> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            Integer temp=0;
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                temp=node.val;
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            result.add(temp);
        }
        return result;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18