标签:log nod highlight 打印 描述 打印二叉树 cpp tle tree
/* 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; } };
标签:log nod highlight 打印 描述 打印二叉树 cpp tle tree
原文地址:http://www.cnblogs.com/dd2hm/p/7460725.html