zoukankan      html  css  js  c++  java
  • Binary Tree Level Order Traversal 解答

    Question

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

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

        3
       / 
      9  20
        /  
       15   7
    

    return its level order traversal as:

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

    Solution -- Two Queues

    Classic solution for BFS problem is to use two queues. One for current level, and the other for next level. This method is to visit tree level by level. Time complexity is O(n), space cost is O(n), n is the number of nodes in tree.

    Deque (Java Interface)

    ArrayDeque (Java Class)

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<List<Integer>> levelOrder(TreeNode root) {
    12         List<List<Integer>> result = new ArrayList<List<Integer>>();
    13         if (root == null)
    14             return result;
    15         Deque<TreeNode> current = new ArrayDeque<TreeNode>();
    16         Deque<TreeNode> next;
    17         TreeNode tmpNode;
    18         current.addLast(root);
    19         while (current.size() > 0) {
    20             // Refresh next queue
    21             next = new ArrayDeque<TreeNode>();
    22             List<Integer> tmpList = new ArrayList<Integer>();
    23             while (current.size() > 0) {
    24                 tmpNode = current.pop();
    25                 if (tmpNode.left != null)
    26                     next.addLast(tmpNode.left);
    27                 if (tmpNode.right != null)
    28                     next.addLast(tmpNode.right);
    29                 tmpList.add(tmpNode.val);
    30             }
    31             // Refresh prev queue
    32             current = next;
    33             result.add(tmpList);
    34         }
    35         return result;
    36     }
    37 }

     Simplied version

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    from collections import deque
    
    class Solution:
        def levelOrder(self, root: TreeNode) -> List[List[int]]:
            result = []
            if not root:
                return result
            queue = deque()
            queue.append(root)
            while queue:
                level = []
                size = len(queue)
                for i in range(size):
                    node = queue.popleft()
                    level.append(node.val)
                    if node.left:
                        queue.append(node.left)
                    if node.right:
                        queue.append(node.right)
                result.append(level)
            return result
  • 相关阅读:
    Nginx安装部署手册
    5种mysql日志分析工具比拼
    分析诊断工具之一:MYSQL性能查看(多指标)
    mysqlsla安装和使用介绍
    Linux下MySQL慢查询分析mysqlsla安装使用
    mysql 开启慢查询及其用mysqldumpslow做日志分析
    MySQL性能诊断与调优
    MySQL慢日志查询分析方法与工具
    MySQL 慢日志分析
    MySQL 慢查询日志(Slow Query Log)
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4834085.html
Copyright © 2011-2022 走看看