题目描述:树的后序遍历
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].
实现:1.递归方式
/**
* 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>&vec){
if(root != NULL){//递归实现,比较简单
postOrder(root->left,vec);
postOrder(root->right,vec);
vec.push_back(root->val);
}
}
vector<int> postorderTraversal(TreeNode *root) {
vector<int> vec;
postOrder(root,vec);
return vec;
}
};
2.非递归方式
需要用栈来保存每次的父节点
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int>vec;
if(root == NULL)
return vec;
stack<TreeNode*>st;
st.push(root);
TreeNode * cur = NULL;
while(!st.empty()){
cur = st.top();
if(cur->left == NULL && cur->right == NULL){
vec.push_back(cur->val);
st.pop();
}else{//进入栈的每个节点都没有左右节点,这样就可以直接出栈
if(cur->right){//将访问过的右节点置为空
st.push(cur->right);
cur->right = NULL;
}
if(cur->left){//<span style="font-family: Arial, Helvetica, sans-serif;">将访问过的左节点置为空</span>
st.push(cur->left);
cur->left = NULL;
}
}
}
return vec;
}
};