102. 二叉树的层次遍历

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / 
  9  20
    /  
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]
vector<vector<int>> levelOrder(TreeNode* root) {//數據結構的層次遍歷
      vector<vector<int>> res;
      if (root == NULL) return res;
      queue<TreeNode*> q;    //指針隊列
      q.push(root);
      while (!q.empty())
      {
          int size = q.size();
          vector<int> tem;
          while (size--)
          {
              TreeNode* tree = q.front();//為頭指針
              tem.push_back(q.front()->val);
              q.pop();
              if (tree->left){
                  q.push(tree->left);
              }

              if (tree->right){
                  q.push(tree->right);
              }
        
          }
          res.push_back(tem);
      }
      return res;
  }//層次遍歷的主要思想:頭指針先入隊列,如果對壘不空,訪問頭節點。如果左子樹不空,進對列。如果右子樹不空,進隊列。
原文地址:https://www.cnblogs.com/binanry/p/10054992.html