标签:二层 顺序 turn class 题目 ++ evel level roo
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> > res; 15 vector<int> temp; 16 int odd = 0; //0表示奇数行,1表示偶数行 17 queue<TreeNode*> q; 18 if (pRoot == NULL) 19 return res; 20 q.push(pRoot); 21 int current = 1, next = 0; //current记录当前打印行的元素数,next表示下一行的元素个数。 22 while (!q.empty()) { 23 temp.clear(); 24 for (int i = 0; i < current; i++) { 25 TreeNode* pNode = q.front(); 26 q.pop(); 27 temp.push_back(pNode->val); 28 if (pNode->left != NULL) { 29 q.push(pNode->left); 30 next++; 31 } 32 if (pNode->right != NULL) { 33 q.push(pNode->right); 34 next++; 35 } 36 } 37 //如果是奇数行,就要将保存下来的逆序保存 38 if (odd == 1) { 39 for (int i = 0; i < (current >> 1); i++) { 40 swap(temp[i], temp[current - 1 - i]); 41 } 42 } 43 res.push_back(temp); 44 odd = 1 - odd; 45 current = next; 46 next = 0; 47 } 48 return res; 49 } 50 };
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> > res; 15 vector<int> temp; 16 stack<TreeNode*> level[2]; 17 int current = 0, next = 1; 18 if (pRoot == NULL) 19 return res; 20 level[current].push(pRoot); 21 //如果pRoot == NULL, 那么压入栈之后,栈非空,而取元素的话,又会产生越界? 22 while (!level[current].empty() || !level[next].empty()) { 23 TreeNode* pNode = level[current].top(); 24 level[current].pop(); 25 temp.push_back(pNode->val); 26 //current == 0表示当前在保存偶数行的数,将下一行的数保存到栈时,先将节点的左孩子放入栈中 27 if (current == 0) { 28 if (pNode->left != NULL) 29 level[next].push(pNode->left); 30 if (pNode->right != NULL) 31 level[next].push(pNode->right); 32 } else { //当前在保存奇数行的数据,先将节点的右孩子放入栈中 33 if (pNode->right != NULL) 34 level[next].push(pNode->right); 35 if (pNode->left != NULL) 36 level[next].push(pNode->left); 37 } 38 if (level[current].empty()) { 39 res.push_back(temp); 40 temp.clear(); 41 current = 1 - current; 42 next = 1 - next; 43 } 44 } 45 return res; 46 } 47 };
标签:二层 顺序 turn class 题目 ++ evel level roo
原文地址:https://www.cnblogs.com/qinduanyinghua/p/11336920.html