阅读 86

[Leetcode][Python/Java]Binary Tree Level Order Traversal/二叉树层序遍历 |刷题打卡

题目大意

实现树的广度优先遍历,每一层上的数据按照从左到右的顺序排列。

解题思路

参考:链接 将树每一层的节点存在一个列表中,遍历列表中的元素,如果该节点有左右节点的话,就把它们加入一个临时列表,这样当遍历结束时,下一层的节点也按照顺序存储好了,不断循环直到下一层的列表为空。

代码

Java

import java.util.*;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }

        ArrayList<Integer> result = new ArrayList<>();
        Deque<TreeNode> deque = new LinkedList<>();
        deque.add(root);
        while (!deque.isEmpty()) {
            TreeNode t = deque.pop();
            if (t.left != null) {
                deque.add(t.left);
            }
            if (t.right != null) {
                deque.add(t.right);
            }
            result.add(t.val);
        }
        return result;
    }
}
复制代码

Python

迭代

BFS

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        tree = []
        if not root:
            return tree
        curr_level = [root]
        # print(type(root), type(curr_level))  # (<class 'precompiled.treenode.TreeNode'>, <type 'list'>)
        # print(curr_level)  # 作为list,却并不能遍历整个树
        while curr_level:
            level_list = []
            next_level = []
            for temp in curr_level:
                level_list.append(temp.val)
                if temp.left:
                    next_level.append(temp.left)
                if temp.right:
                    next_level.append(temp.right)
            tree.append(level_list)
            curr_level = next_level
        return tree
复制代码

补充:

递归

class Solution(object):
    def preorder(self, root, level, res):
        if root:
            if len(res) < level+1: res.append([])
            res[level].append(root.val)
            self.preorder(root.left, level+1, res)
            self.preorder(root.right, level+1, res)
            
    def levelOrder(self, root):
        res=[]
        self.preorder(root, 0, res)
        return res
复制代码

本文正在参与「掘金 2021 春招闯关活动」, 点击查看 活动详情

文章分类
阅读
文章标签