题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推
/* 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>>ret; if(!pRoot) return ret; stack<TreeNode*> stack[2]; int cur=0; int next=1; stack[cur].push(pRoot); vector<int> curVec; while(!stack[0].empty() || !stack[1].empty()) { TreeNode * pNode=stack[cur].top(); curVec.push_back(pNode->val); stack[cur].pop(); if(cur==0) { if(pNode->left) stack[next].push(pNode->left); if(pNode->right) stack[next].push(pNode->right); } else { if(pNode->right) stack[next].push(pNode->right); if(pNode->left) stack[next].push(pNode->left); } if(stack[cur].empty()) { ret.push_back(curVec); curVec.clear(); cur=1-cur; next=1-next; } } return ret; } };
按之字形顺序打印二叉树
class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int> > result; if (pRoot == NULL) return result; stack<TreeNode*> stk1, stk2; stk1.push(pRoot); // stk1 存储奇数层;stk2 存储偶数层 while (!stk1.empty() || !stk2.empty()) { vector<int> level_vec; if (!stk1.empty()) { while (!stk1.empty()) { TreeNode* pTop = stk1.top(); level_vec.push_back(pTop->val); if (pTop->left != NULL) // 入栈先左后右,出栈时从右向左(偶数层) stk2.push(pTop->left); if (pTop->right != NULL) stk2.push(pTop->right); stk1.pop(); } } else { while (!stk2.empty()) { TreeNode* pTop = stk2.top(); level_vec.push_back(pTop->val); if (pTop->right != NULL) // 入栈先右后左,出栈时先左后右(奇数层) stk1.push(pTop->right); if (pTop->left != NULL) stk1.push(pTop->left); stk2.pop(); } } result.push_back(level_vec); } return result; } };
层次遍历加上判断奇偶改变方向就行
/* 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(pRoot==NULL) return res; queue<TreeNode*> que; que.push(pRoot); bool even=false; while(!que.empty()) { vector<int> vec; const int size=que.size(); for(int i=0;i<size;i++) { TreeNode * tmp=que.front(); que.pop(); vec.push_back(tmp->val); if(tmp->left !=NULL) que.push(tmp->left); if(tmp->right!=NULL) que.push(tmp->right); } if(even) reverse(vec.begin(),vec.end()); res.push_back(vec); even=!even; } return res; } };