标签:间接 一个 ack public 1.7 奇数 其他 有一个 log
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 }; 10 */ 11 class Solution { 12 public: 13 vector<vector<int> > Print(TreeNode* pRoot) { 14 vector<vector<int> > result; 15 vector<int> temp;//每一行的间接变量 16 if(pRoot == NULL) 17 return result; 18 stack<TreeNode *> levels[2];//0存奇数行,1存偶数行 19 int current = 0; 20 int next = 1; 21 levels[current].push(pRoot); 22 while(!levels[0].empty() || !levels[1].empty()) 23 { 24 TreeNode *pNode = levels[current].top(); 25 levels[current].pop(); 26 temp.push_back(pNode->val); 27 if(current == 0)//奇数行,先存左子结点,再存右子结点 28 { 29 if(pNode->left != NULL) 30 levels[next].push(pNode->left); 31 if(pNode->right != NULL) 32 levels[next].push(pNode->right); 33 } 34 else//偶数行,先存右子结点,再存左子结点 35 { 36 if(pNode->right != NULL) 37 levels[next].push(pNode->right); 38 if(pNode->left != NULL) 39 levels[next].push(pNode->left); 40 } 41 if(levels[current].empty())//换行 42 { 43 result.push_back(temp); 44 temp.clear();//每行存入完记得清空 45 current = 1 - current; 46 next = 1- next; 47 } 48 } 49 return result; 50 } 51 };
标签:间接 一个 ack public 1.7 奇数 其他 有一个 log
原文地址:http://www.cnblogs.com/qqky/p/7115305.html