Leetcode 之Binary Tree Postorder Traversal(44)

Posted 牧马人夏峥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 之Binary Tree Postorder Traversal(44)相关的知识,希望对你有一定的参考价值。

层序遍历,使用队列将每层压入,定义两个队列来区分不同的层。

vector<vector<int>> levelorderTraversal(TreeNode *root)
      {
          vector<vector<int>> result;
          vector<int>tmp;
          //通过两个queue来区分不同的层次
          queue<TreeNode *>current,next;
          TreeNode *p = root;
          current.push(p);
          while (!current.empty())
          {
              while (!current.empty())
              {
                  p = current.front();
                  current.pop();
                  tmp.push_back(p->val);
                  if (p->left != nullptr)next.push(p->left);
                  if (p->right != nullptr)next.push(p->right);
              }
              result.push_back(tmp);
              tmp.clear();
              //交换并将next清空,
              swap(current, next);
          }

          return result;
      }
View Code

 

以上是关于Leetcode 之Binary Tree Postorder Traversal(44)的主要内容,如果未能解决你的问题,请参考以下文章