题目:
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
思想:
递归调用和非递归调用两种方式。对于非递归调用,假设T是要遍历的根指针,后序遍历是要求在遍历完左右子树后再遍历根节点。因此需要判断左右子树是否遍历过。这里采用标记法,(tag为0表示左子树未遍历,tag为1表示右子树未遍历)。
代码:
/**
* Definition for a binary tree node.
**/
typedef struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
bool tag;//采用标志位来进行后序遍历
TreeNode(int x) : val(x),tag(false), left(NULL), right(NULL) {}
}*BinaryTree;
class Solution {
public:
void CreateTree(BinaryTree &T)
{
char data;
cin >> data;
if (data == '#')
T = NULL;
else
{
T = new TreeNode(data - '0');
CreateTree(T->left);
CreateTree(T->right);
}
}
void postorder(TreeNode*root, vector<int>&ret)
{
if (root != NULL)
{
postorder(root->left, ret);
postorder(root->right, ret);
ret.push_back(root->val);
}
}
vector<int> postorderTraversal(TreeNode* root) {//递归
vector<int> ret;
postorder(root, ret);
return ret;
}
vector<int> postorderTraversal2(TreeNode* root) {//非递归
stack<TreeNode *> s;
TreeNode * p = root;
vector<int> ret;
while (p!=NULL|| s.empty())
{
while (p!=NULL)
{
s.push(p);
p = p->left;
}
if (!s.empty())
{
p = s.top();
if (p->tag)
{
ret.push_back(p->val);
s.pop();
p = NULL;
}
else
{
p->tag = true;
p = p->right;
}
}
}
}
};