『模板』题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; */ class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { vector< vector<int> > res; if( nullptr==pRoot ) { return res; } queue< TreeNode * > solve; solve.push( pRoot ); int count=1; int tag=1;//表示正序 while( !solve.empty() ) { vector<int> temp; int countTemp=0; while( count-- ) { TreeNode * Help=solve.front(); solve.pop(); temp.push_back( Help->val ); if( nullptr!=Help->left ) { solve.push( Help->left ); ++countTemp; } if( nullptr!=Help->right ) { solve.push( Help->right ); ++countTemp; } } count=countTemp; if( -1==tag ) { reverse( temp.begin(), temp.end() ); } res.push_back(temp); tag*=( -1 ); } return res; } };