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

按之字形顺序打印二叉树

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;
    }

};

全部评论

相关推荐

07-07 11:33
江南大学 Java
已经在暑假实习了&nbsp;,没有明确说有hc,纠结实习到八月份会不会有点影响秋招毕竟感觉今年好多提前批
程序员小白条:92的话准备提前批,其他没必要,没面试机会的,而且你要准备充分,尤其八股和算法题
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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