题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

/*
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 == NULL)
            return {};
        vector<vector<int>> myTwoVec;
        list<TreeNode*> mylist;
        mylist.push_back(pRoot);
        int mode = 0; // 0: left to right, 1: right to left
        while (!mylist.empty()) {
            int n = mylist.size();
            vector<int> myVect{};
            for (int i = 0; i < n; i++) {
                TreeNode* frt;
                switch (mode) {
                    case 0:
                        frt = mylist.front();
                        mylist.pop_front();
                        if (frt->left)
                            mylist.push_back(frt->left);
                        if (frt->right)
                            mylist.push_back(frt->right);
                        break;

                    default:
                        frt = mylist.back();
                        mylist.pop_back();
                        if (frt->right)
                            mylist.push_front(frt->right);
                        if (frt->left)
                            mylist.push_front(frt->left);
                        break;
                }
                myVect.push_back(frt->val);
            }
            mode = mode ? 0 : 1;
            myTwoVec.push_back(myVect);
        }
        return myTwoVec;
    }

};

全部评论

相关推荐

买蜜雪也用卷:已经挂了六页了
点赞 评论 收藏
分享
2024-12-06 10:44
东北财经大学 运营
在拧螺丝的西红柿很热情:工作量数据化,你的实习我只看到了一个30%,比如总浏览量十万加,同比增长20%,用户复购率达到70%等等,自己根据你当时的工作情况挖掘吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务