Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree
Given binary tree
{1,#,2,3}
,1 \ 2 / 3
return
[3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode *root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. stack<TreeNode *> buffer; vector<int> output; if (root == NULL) return output; buffer.push(root); while (!buffer.empty()) { TreeNode *temp = buffer.top(); if (temp->right == NULL && temp->left == NULL) { output.push_back(temp->val); buffer.pop(); while (!buffer.empty() && (buffer.top()->left == temp || buffer.top()->right == temp) ) { temp = buffer.top(); output.push_back(temp->val); buffer.pop(); } } else { if (temp->right != NULL) buffer.push(temp->right); if (temp->left != NULL) buffer.push(temp->left); } } return output; } };
3 comments:
谢谢,一直看你的code,学习了
很高兴能有用 哈哈
赞一个!
Post a Comment