二叉树的Zigzag遍历

二叉树的Zigzag遍历_第1张图片

是什么是Zigzag遍历,简单点说就是层序遍历的升级版,首先,我们要设置一个LefttoRight的bool变量,通过一个bool变量来控制当前层是从左往右压还是从右往左压。当然,在这里我还对之前的层序遍历进行了进一步的更新:

vector> ZigzaglevelOrder(TreeNode* root)
{
   vector> result;
   if(root==nullptr||root->next==nullptr) return root;
   queue que;
   bool LefttoRight=true;
   que.push(root);
   while(!que.empty())
   {
     int size=que.size();
     vector low(size);
     for(int i=0;ival;
       if(root->left!=nullptr)
          que.push(root->left);
       if(root->right!=nullptr)
          que.push(root->right);
     }
     LefttoRight=!LefttoRight;
     result.push_back(low);
    }
return result;
}

 

你可能感兴趣的:(数据结构与leetcode)