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
  • 相关阅读:
    js面向对象和PHP面相对象
    git
    css3动画、2D与3D效果
    渲染数据方式
    ajax
    面向对象
    Date 日期
    Math 数值对象
    What is CGLib and JDK动态代理
    IDEA中lock对象不提示newCondition();
  • 原文地址:https://www.cnblogs.com/asenyang/p/9739248.html
Copyright © 2011-2022 走看看