Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LC107. 二叉树的层次遍历 #26

Open
HealUP opened this issue May 18, 2023 · 0 comments
Open

LC107. 二叉树的层次遍历 #26

HealUP opened this issue May 18, 2023 · 0 comments
Labels
算法 记录刷题记录,代码随想录

Comments

@HealUP
Copy link
Owner

HealUP commented May 18, 2023

3.2 107. 二叉树的层次遍历

class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        /*思路:
        1.广搜得到二维数组的结果
        2.将二维数组反转
         */
        //创建一个结果二维数组
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> que = new LinkedList<>();
        if (root == null) {
            return res;
        }
        que.offer(root);//根节点放入队列
        while (!que.isEmpty()) {
            //创建一维数组保存当前层的节点
            List<Integer> list = new ArrayList<>();
            //保存当前层的节点的数量
            int len = que.size();
            for (int i = 0; i < len; i++) {
                //保存当前出队的节点
                TreeNode node = que.poll();
                //将其值存入到一维数组
                list.add(node.val);
                //将该节点的左右节点入队
                if (node.left != null) que.offer(node.left);//空节点不入队
                if (node.right != null) que.offer(node.right);
            }
            //将该层的节点的值存放到一维数组中
            res.add(list);
        }
        //开辟一个二维数组的空间,存放反转后的二维数组的结果
        List<List<Integer>> result = new ArrayList<>();
        for (int i = res.size() - 1; i >= 0; i--) {//数组下标从0开始,最大长度是数组大小减1
            result.add(res.get(i));//get获取对应位置的元素
        }

        //返回结果
        return result;
    }
}
@HealUP HealUP added 算法 记录刷题记录,代码随想录 二叉树 labels May 18, 2023
@HealUP HealUP removed the 二叉树 label Jul 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
算法 记录刷题记录,代码随想录
Projects
None yet
Development

No branches or pull requests

1 participant