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

把二叉树打印成多行

https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288

/*
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) {
        vector<vector<int> > res;
        if (pRoot == nullptr) {
            return res;
        }
        deque<TreeNode*> myDeque;
        myDeque.push_back(pRoot);
        while (!myDeque.empty()) {
            vector<int> curVec;
            int szLen = static_cast<int>(myDeque.size());
            for (int i = 0; i < szLen; i++) {
                TreeNode* frontNode = myDeque.front();
                curVec.push_back(frontNode->val);
                myDeque.pop_front();
                if (frontNode->left != nullptr) {
                    myDeque.push_back(frontNode->left);
                }
                if (frontNode->right != nullptr) {
                    myDeque.push_back(frontNode->right);
                }
            }
            res.push_back(curVec);
        }
        return res;
    }

};

全部评论

相关推荐

努力学习的小绵羊:我反倒觉得这种挺好的,给不到我想要的就别浪费大家时间了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务