[LeetCode] 102. Binary Tree Level Order Traversal 二叉树层序遍历

2021年09月15日 阅读数:1
这篇文章主要向大家介绍[LeetCode] 102. Binary Tree Level Order Traversal 二叉树层序遍历,主要内容包括基础应用、实用技巧、原理机制等方面,希望对大家有所帮助。

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

For example:
Given binary tree {3,9,20,#,#,15,7},java

    3
   / \
  9  20
    /  \
   15   7

 

return its level order traversal as:node

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

给一棵二叉树,返回从左往右层序遍历的结果,每一层单独记录。有BFS(迭代Iteration)和DFS(递归Recursion)两种解法。python

拓展:先序遍历preorder的递归作法加上一个层就是这题的DFS解法。app

Java: Iteration, T: O(n), S: O(1)ide

public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List result = new ArrayList();

        if (root == null) {
            return result;
        }

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            ArrayList<Integer> level = new ArrayList<Integer>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode head = queue.poll();
                level.add(head.val);
                if (head.left != null) {
                    queue.offer(head.left);
                }
                if (head.right != null) {
                    queue.offer(head.right);
                }
            }
            result.add(level);
        }

        return result;
    }
}  

Java: Recursion, T: O(n), S: O(n)post

public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        traverse(root, 1, result);
        return result;
    }

    void traverse(TreeNode root, int level,
                  List<List<Integer>> result) {
        if (root == null) return;

        if (level > result.size())
            result.add(new ArrayList<>());

        result.get(level-1).add(root.val);
        traverse(root.left, level+1, result);
        traverse(root.right, level+1, result);
    }
}

Python: Iterationurl

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def levelOrder(self, root):
        if root is None:
            return []
        result, current = [], [root]
        while current:
            next_level, vals = [], []
            for node in current:
                vals.append(node.val)
                if node.left:
                    next_level.append(node.left)
                if node.right:
                    next_level.append(node.right)
            current = next_level
            result.append(vals)
        return result  

Python:code

class Solution(object):
    def levelTraversal(self, root):
        if not root:
            return []
        result, queue = [], [root]
        while queue:
            vals = []
            for i in range(len(queue)):
                node = queue.pop(0) 
                vals.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            if vals:
                result.append(vals)

        return result 

Python: Recursivehtm

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def levelTraversal(self, root):
        res = []
        self.recur(root, 1, res)
        return res

    def recur(self, node, level, res):
        if not node:
            return

        if len(res) < level:
            res.append([])
        res[level - 1].append(node.val)
        self.recur(node.left, level + 1, res)
        self.recur(node.right, level + 1, res)


if __name__ == '__main__':
    node = TreeNode(3)
    node.left = TreeNode(9)
    node.right = TreeNode(20)
    node.right.left = TreeNode(15)
    node.right.right = TreeNode(7)
    print Solution().levelTraversal(node) 

Python: Recursive

class Solution:
    # @param root, a tree node
    # @return a list of lists of integers
    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

C++:

class Solution {
public:
    vector<vector<int> > levelOrder(TreeNode *root) {
        vector<vector<int> > res;
        if (root == NULL) return res;

        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            vector<int> oneLevel;
            int size = q.size();
            for (int i = 0; i < size; ++i) {
                TreeNode *node = q.front();
                q.pop();
                oneLevel.push_back(node->val);
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }
            res.push_back(oneLevel);
        }
        return res;
    }
};

C++: Recursion

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int> > res;
        levelorder(root, 0, res);
        return res;
    }
    void levelorder(TreeNode *root, int level, vector<vector<int> > &res) {
        if (!root) return;
        if (res.size() == level) res.push_back({});
        res[level].push_back(root->val);
        if (root->left) levelorder(root->left, level + 1, res);
        if (root->right) levelorder(root->right, level + 1, res);
    }
};

 

相似题目:

[LeetCode] 107. Binary Tree Level Order Traversal II 二叉树层序遍历 II

[LeetCode] 199. Binary Tree Right Side View 二叉树的右侧视图

 

All LeetCode Questions List 题目汇总