按之字形顺序打印二叉树
Posted 王小东大将军
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了按之字形顺序打印二叉树相关的知识,希望对你有一定的参考价值。
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推
/* 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; } };
以上是关于按之字形顺序打印二叉树的主要内容,如果未能解决你的问题,请参考以下文章