zoukankan      html  css  js  c++  java
  • leetcode102

    本题是广度优先遍历(BFS)实现树的层次遍历,使用队列实现。

    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> res;
            queue<TreeNode*>q;                
            if (root != NULL)
            {
                q.push(root);
                while (!q.empty())
                {
                    vector<int> tmp;
                    vector<TreeNode*> T;
                    while (!q.empty())
                    {
                        TreeNode* t = q.front();
                        q.pop();
                        tmp.push_back(t->val);
                        if (t->left != NULL)
                        {
                            T.push_back(t->left);
                        }
                        if (t->right != NULL)
                        {
                            T.push_back(t->right);
                        }
                    }                
                    res.push_back(tmp);
                    for (auto x : T)
                    {
                        q.push(x);
                    }
                }
            }
            return res;
        }
    };

    补充一个python的实现:

     1 class Solution:        
     2     def lOrder(self,temp,result):
     3         count = len(temp)
     4         newary = []
     5         while count > 0:
     6             top = temp.pop(0)
     7             newary.append(top.val)
     8             count -= 1
     9             if top.left != None:
    10                 temp.append(top.left)
    11             if top.right != None:
    12                 temp.append(top.right)
    13         if len(newary) > 0:
    14             result.append(newary)
    15         if len(temp) > 0:
    16             self.lOrder(temp,result)
    17         
    18     def levelOrder(self, root: TreeNode) -> List[List[int]]:
    19         result = []
    20         temp = []
    21         if root != None:
    22             temp.append(root)
    23             self.lOrder(temp,result)
    24         return result
  • 相关阅读:
    2017 北京商改住政策
    python3 进程和线程(二)
    python3 pymysql
    SQL基本操作
    python3 paramiko
    python3 classmethod
    python3 property
    LVS负载均衡
    flume介绍及应用
    关系型数据库和非关系型数据库介绍及优劣势比较
  • 原文地址:https://www.cnblogs.com/asenyang/p/9739248.html
Copyright © 2011-2022 走看看