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?
本题是二叉树的后序遍历,要使用非递归算法。递归算法的解是很简单,代码如下:
/**
* 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> ans;
vector<int> postorderTraversal(TreeNode *root) {
if(root==NULL) return ans;
postorderTraversal(root->left);
postorderTraversal(root->right);
ans.push_back(root->val);
return ans;
}
};
非递归的后序遍历需要用堆栈实现,看了网上的题解才知道。需要一个cur记录目前访问的节点。当一个节点是叶子节点或者它的左子树和右子树已经访问过了,则将它从堆栈中弹出。右儿子先入栈,接下来是左儿子。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
list <TreeNode *> tree_list;
vector<int> ans;
vector<int> postorderTraversal(TreeNode *root) {
if(root == NULL) return ans;
tree_list.push_front(root);
TreeNode *head = root;
while(!tree_list.empty()){
TreeNode *cur = tree_list.front();
if((cur->left==NULL && cur->right == NULL)|| cur->left == head || cur->right == head){
tree_list.pop_front();
ans.push_back(cur->val);
head = cur;
}
else{
if(cur->right != NULL) tree_list.push_front(cur->right);
if(cur->left != NULL) tree_list.push_front(cur->left );
}
}
return ans;
}
};