LeetCode刷题集Android技术知识Android开发

Day52 二叉树的层序遍历

2021-03-19  本文已影响0人  Shimmer_

给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)

https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

示例1:

二叉树:[3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7

[
[3],
[9,20],
[15,7]
]

Java解法

思路:

  • 层序边历,通过栈缓存当前数据,因为先进后出,所以先存储右节点,
  • 优化使用队列来存储,但效率没有太多提升
package sj.shimmer.algorithm.m3_2021;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;

import sj.shimmer.algorithm.TreeNode;

/**
 * Created by SJ on 2021/3/18.
 */

class D52 {
    public static void main(String[] args) {
        System.out.println(levelOrder(TreeNode.getInstance(new Integer[]{3, 9, 20, null, null, 15, 7})));
        System.out.println(levelOrder(TreeNode.getInstance(new Integer[]{1, 2, 3, 4, null, null, 5})));
        System.out.println(levelOrder(TreeNode.getInstance(new Integer[]{3, 9, 20, null, null, 15, 7})));
    }
    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> results = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        if (root != null) {
            queue.add(root);
        }
        while (!queue.isEmpty()) {
            List<Integer> tempList = new ArrayList<>();
            Queue<TreeNode> temp = new ArrayDeque<>();
            while (!queue.isEmpty()) {
                TreeNode poll = queue.poll();
                tempList.add(poll.val);
                if (poll.left != null) {
                    temp.add(poll.left);
                }
                if (poll.right != null) {
                    temp.add(poll.right);
                }
            }
            results.add(tempList);
            queue = temp;
        }
        return results;
    }
    public static List<List<Integer>> levelOrder1(TreeNode root) {
        List<List<Integer>> results = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root != null) {
            stack.add(root);
        }
        while (!stack.isEmpty()){
            List<Integer> tempList = new ArrayList<>();
            Stack<TreeNode> temp = new Stack<>();
            while (!stack.isEmpty()) {
                TreeNode pop = stack.pop();
                if (pop != null) {
                    tempList.add(pop.val);
                    temp.add(pop.left);
                    temp.add(pop.right);
                }
            }
            if (tempList.size()!=0) {
                results.add(tempList);
                while (!temp.isEmpty()) {
                    stack.add(temp.pop());
                }
            }
        }
        return results;
    }
}
image image

官方解

https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/er-cha-shu-de-ceng-xu-bian-li-by-leetcode-solution/

  1. 广度优先搜索

    相较我的处理,优化了临时存储

    • 时间复杂度:O(n)

    • 空间复杂度:O(n)

上一篇下一篇

猜你喜欢

热点阅读