【LeetCode】No.102. Binary Tree Level Order Traversal -- Java Version

91 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第19天,点击查看活动详情.

题目链接:leetcode.com/problems/bi…

1. 题目介绍(Binary Tree Level Order Traversal)

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

【Translate】: 给定二叉树的根,返回其节点值层序遍历。(即从左到右,逐层排列)。

【测试用例】:

示例1:

testcase1

示例2:

testcase2

【条件约束】:

Constraints

2. 题解

2.1 队列 - 广度优先搜索(BFS)

原题解来自于 sgallivan 的 JS, Python, Java, C++ | Easy BFS Queue Solution w/ Explanation.

二叉树级顺序遍历通常推荐使用队列数据结构的广度优先搜索(BFS)方法。当我们处理一个节点(curr)时,我们将按我们想要遍历的顺序(在本例中,从左到右)将该节点的子节点推到队列的末尾。通过这种方式,我们将在完成遍历该行的同时完成将下一行放入队列。

为了帮助我们跟踪行,我们只需将主循环嵌套在另一个循环中。在外部循环的开始,我们捕获队列长度,它将告诉我们行有多长。然后,我们可以遍历这些节点,每次将它们从队列的前端取出,然后处理任何行尾指令。在这个问题中,这将意味着将当前行数组(row)推到我们的答案数组(ans)上。

我们将继续这个过程,直到队列为空,这时我们将到达二叉树的末尾,并返回ans。

  • Time Complexity: O(N) where N is the number of nodes in the binary tree
  • Space Complexity: O(N) for our answer array
/**
 * 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<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if(root == null) return ans;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        
        while(!queue.isEmpty()){
            int qlen = queue.size();
            List<Integer> row = new ArrayList<>();
            for(int i = 0; i < qlen; i++){
                TreeNode curr = queue.poll();
                row.add(curr.val);
                if (curr.left != null) queue.add(curr.left);
                if (curr.right != null) queue.add(curr.right);
            }
            ans.add(row);
        }
        return ans;
    }
}

act1

3. 参考资料

[1] Java Deque接口 使用方法(栈、队列、双端队列)| CSDN

[2] Java 双端队列,队列,栈 --- Deque使用指南 | CSDN