题解 | #把二叉树打印成多行#

把二叉树打印成多行

https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=265&rp=1&ru=%2Fexam%2Foj%2Fta&qru=%2Fexam%2Foj%2Fta&sourceUrl=%2Fexam%2Foj%2Fta%3FjudgeStatus%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D13%26type%3D265&difficulty=&judgeStatus=3&tags=&title=&gioEnter=menu

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
  //  层次遍历
        vector<vector<int> > Print(TreeNode* pRoot) {
          if (pRoot == nullptr) {
            return std::vector<std::vector<int>>();
          }
          
          std::vector<std::vector<int>> res;
          std::queue<TreeNode *> s;
          s.push(pRoot);
          
          while (!s.empty()) {
            int size = s.size();
            std::vector<int> tmp;
            
            for (int i = 0; i < size; ++i) {
              TreeNode *root = s.front();
              s.pop();
              tmp.push_back(root->val);
              
              if (root->left) {
                s.push(root->left);
              }
              if (root->right) {
                s.push(root->right);
              }
            }
            
            res.push_back(tmp);
          }
          
          return res;
        }
    
};
全部评论

相关推荐

七牛云头号黑子:人家是过度包装被看出来没过简历,你是包都不包啊兄弟
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务