层次遍历+双向队列

按之字形顺序打印二叉树

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

 vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int>> res;
        if(pRoot==nullptr)return res;
        deque<TreeNode*> Q;
        Q.push_back(pRoot);
        bool flag=true;
        while(!Q.empty()){
            int sz=Q.size();
             vector<int> tmp;
             if(flag){
                  while(sz--){
                     TreeNode* node=Q.front();Q.pop_front();
                     tmp.push_back(node->val);
                     if(node->left) {Q.push_back(node->left);} 
                     if(node->right){Q.push_back(node->right);}
                  }
             }else{
                  while(sz--){
                     TreeNode* node=Q.back();Q.pop_back();
                     tmp.push_back(node->val);
                     if(node->right){Q.push_front(node->right);}
                     if(node->left){Q.push_front(node->left);} 
                  }
             }
            res.push_back(tmp);
            flag=!flag;
        }
        return res;
    }
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务