z字形遍历二叉树

#include <bits/stdc++.h>

using namespace std;

struct TreeNode {
public:
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};

vector<vector<int>> Print(TreeNode* pRoot){
  vector<vector<int>> res;
  if(pRoot == nullptr)
    return res;
  stack<TreeNode*> s0, s1; // s0, left->right,; s1: right->left
  s0.push(pRoot);
  while(!s0.empty() || !s1.empty()){
    vector<int> vv;
    if(!s0.empty()){
      while(!s0.empty()){
	TreeNode* tmp = s0.top();
	s0.pop();
	vv.push_back(tmp->val);
	if(tmp->left !=nullptr){
	  s1.push(tmp->left);
	}
	if(tmp->right !=nullptr){
	  s1.push(tmp->right);
	}
      }
      res.push_back(vv); 
    }
    else if(!s1.empty()){ // if - else if is important, it means only one of condition is satisfied
      while(!s1.empty()){
	TreeNode* tmp = s1.top();
	s1.pop();
	vv.push_back(tmp->val);
	if(tmp->right != nullptr){
	  s0.push(tmp->right);
	}
	if(tmp->left !=nullptr){
	  s0.push(tmp->left);
	}
      }	
      res.push_back(vv);
    }
  }
  return res;
}

    原文作者:Z字形编排问题
    原文地址: https://blog.csdn.net/weixin_39705503/article/details/79890529
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞