另一种自己写的解法
class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int> > result; vector<int> res; if(pRoot == NULL) return result; stack<TreeNode* > sta1; stack<TreeNode* > sta2; int next = 2; sta1.push(pRoot); while(sta1.size() != 0 || sta2.size() != 0){ if(next % 2 == 0){ if(sta1.empty()){ next++; result.push_back(res); res.clear(); } else{ TreeNode* Node = sta1.top(); res.push_back(Node->val); if(Node->left != NULL) sta2.push(Node->left); if(Node->right != NULL) sta2.push(Node->right); sta1.pop(); } } else{ if(sta2.empty()){ next++; result.push_back(res); res.clear(); } else{ TreeNode* Node = sta2.top(); res.push_back(Node->val); if(Node->right != NULL) sta1.push(Node->right); if(Node->left != NULL) sta1.push(Node->left); sta2.pop(); } } } result.push_back(res); return result; } };
时间: 2024-10-11 11:59:39