递归方法:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void postOrder(TreeNode* root, vector<int> &path)
{
if(root!=NULL)
{
postOrder(root->left, path);
postOrder(root->right, path);
path.push_back(root->val); //添加标记位
}
}
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.
vector<int> path;
postOrder(root, path);
return path;
}
};
非递归方法:
**
* 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) {
vector<int> path;
if(root==NULL) return path;
stack<TreeNode*> stk;
stk.push(root);
TreeNode* cur = NULL;
while(!stk.empty())
{
cur = stk.top();
if(cur->left ==NULL && cur->right ==NULL) //为何会存在除了叶子节点还有别的节点符合这个要求
{
path.push_back(cur->val);
stk.pop();
}else{
if(cur->right)
{
stk.push(cur->right);
cur->right = NULL; //在此处进行了处理,为了便于输出
}
if(cur->left)
{
stk.push(cur->left);
cur->left = NULL;
}
}
}
return path;
}
};