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

按之字形顺序打印二叉树

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

#include <iostream>
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        stack<TreeNode*> st;//从左往右,显示,将下一层,从左往右顺序压入栈st1中,准备从右向左出栈
        stack<TreeNode*> st1;//从右往左显示,将下一层按从右向左顺序,压入栈st,准备从左向右出栈
        if(pRoot != NULL) st.push(pRoot); //将根结点,压入st中
        vector<vector<int>> result;//创建返回二级向量
        int count = 0;//记录顺序
        while(!st.empty() || !st1.empty()){
            vector<int> vec;
            int size = st.size(); // 读取从左往右的栈内元素个数,挨个出栈
            int size1 = st1.size();//读取从右向左的栈内元素个数,挨个出栈
            
            count++;
            if(count % 2 == 1){
                for(int i = 0; i < size; i++){
                    TreeNode* node = st.top();
                    st.pop();
                    vec.push_back(node->val);
                    if(node->left) st1.push(node->left);
                    if(node->right) st1.push(node->right);
                   
                }
            }
            else if(count % 2 == 0)
            {   
                for(int i = 0; i < size1; i++){
                    TreeNode* node = st1.top();
                    st1.pop();
                    vec.push_back(node->val);
                    if(node->right) st.push(node->right);
                    if(node->left) st.push(node->left);
                }
            }    
            result.push_back(vec);//压入向量
        }
        return result;
    }
    
};

全部评论

相关推荐

程序员鼠鼠_春招版:我要12k吧我挂了,还招呢,天天被割,这点钱都不舍得出
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务