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

按之字形顺序打印二叉树

http://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 > Print(TreeNode pRoot) { vector<vector>res; if(pRoot==nullptr)return res; int flag=0; stack<TreeNode *>st; queue<TreeNode *>qu; st.push(pRoot); while(!st.empty()){ int size=st.size(); // if(size==4)return res; // TreeNode *p=qu.front(); // qu.pop();

        vector<int>vec;
        while(size--){

// vec.clear(); TreeNode *p=st.top(); st.pop(); vec.push_back(p->val); qu.push(p); } if(!vec.empty())res.push_back(vec); if(!qu.empty()){ int size_qu=qu.size(); while(size_qu--){ TreeNode *q=qu.front(); qu.pop(); if((flag%2)==1){ if(q->right)st.push(q->right); if(q->left)st.push(q->left); }else{ if(q->left)st.push(q->left); if(q->right)st.push(q->right); } } } flag++; } return res; }

};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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