z字形遍历二叉树

#include 

using namespace std;

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

vector> Print(TreeNode* pRoot){
  vector> res;
  if(pRoot == nullptr)
    return res;
  stack s0, s1; // s0, left->right,; s1: right->left
  s0.push(pRoot);
  while(!s0.empty() || !s1.empty()){
    vector 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;
}

你可能感兴趣的:(算法,基础)