劍指offer61 按之字形順序打印二叉樹
阿新 • • 發佈:2017-07-24
push_back 打印 pre logs cto pan 順序 code pty
另一種自己寫的解法
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; } };
劍指offer61 按之字形順序打印二叉樹