给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> result;
vector<int> postorderTraversal(TreeNode* root) {
LRD(root);
return result;
}
void LRD(TreeNode* root)
{
if(root==NULL) return;
LRD(root->left);
LRD(root->right);
result.push_back(root->val);
}
};
此方法为递归调用
/**
* Definition for a binary tree node.
* 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) {
stack<TreeNode*> s1;
stack<TreeNode*> s2;
vector<int> res;
if (root == NULL)
return res;
TreeNode* p = root;
s1.push(root);
while (!s1.empty())
{
p=s1.top();
s1.pop();
s2.push(p);
if (p->left != NULL)
s1.push(p->left);
if (p->right != NULL)
s1.push(p->right);
}
while (!s2.empty())
{
p = s2.top();
res.push_back(p->val);
s2.pop();
}
return res;
}
};
此方法迭代