题目描述

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
 
某一层 的结点数--> 非递归方法。。。
关键:出队前 ,队列的大小,就是这一层的结点数。。。。。记录出队结点数目cur,和队列大小     while(cur<size){ 出一个(更新cur),进两个(改变队列现在大小,但是不改变size大小), }
 
vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> >result;
        if(pRoot==NULL) return result;
        queue<TreeNode*> que;
        que.push(pRoot);
        int depth=0;
        while(que.size()!=0){
            ++depth;
            int cur=0;
            int size=que.size();//当前层 元素 个数
            vector<int>re;
            while(cur<size){
                TreeNode* p=que.front();
                re.push_back(p->val);
                que.pop();
                ++cur;
                if(p->left)
                    que.push(p->left);
                if(p->right)
                    que.push(p->right);
            }
            if(!((depth+1)%2==0)){
                int temp=0;
                for(int i=0;i<re.size()/2;++i){
                    temp=re[i];
                    re[i]=re[re.size()-1-i];
                    re[re.size()-1-i]=temp;
                }                
            }
            result.push_back(re);              
        }
        return result;
    }
 
按层 打印,, 两个队列,
or 两个stack,每个记录当前层;
 
stack1.push(head);
stack2;
while(stack1||stacke2){  
  while(stack1){
    *node p=stack1.top();
    stack1.pop();
    if(p->left)
        stacke2.push(p->left);
    if(p->right)    
      stacke2.push(p->right);
  }
  while(stack2){
    *node p=stack2.top();
    stack2.pop();
    if(p->left)
        stacke1.push(p->right);  //之 字型,所以这里先右再左。
    if(p->right)    
      stacke1.push(p->left);
  }
}