From : https://leetcode.com/problems/binary-tree-postorder-traversal/
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]
.
/**
* 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) {
vector<int> postorder_vec;
TreeNode *cur=root; //定义指针,指向当前节点
TreeNode *pre=NULL; //定义指针,指向上一各访问的节点
if(cur==NULL) return postorder_vec;
stack<TreeNode *> postorder_stack;//创建一个空栈
postorder_stack.push(cur);//先将树的根节点入栈
//直到栈空时,结束循环
while(!postorder_stack.empty()) {
cur=postorder_stack.top();//当前节点置为栈顶节点
if((cur->left==NULL&&cur->right==NULL)||((pre!=NULL)&&(cur->left==pre||cur->right==pre))) {
//如果当前节点没有左右孩子,或者有左孩子或有孩子,但已经被
//访问输出,则直接输出该节点,将其出栈,将其设为上一个访问的节点
postorder_stack.pop();
postorder_vec.push_back(cur->val);
pre=cur;
} else {
//如果不满足上面两种情况,则将其右孩子左孩子依次入栈
if(cur->right!=NULL) postorder_stack.push(cur->right);
if(cur->left!=NULL) postorder_stack.push(cur->left);
}
}
}
};
/**
* 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) {
vector<int> rs;
if (!root) return rs;
stack<TreeNode *> stk;
stk.push(root);
while(!stk.empty()) {
TreeNode *t = stk.top();
stk.pop();
rs.push_back(t->val);
//注意,下面入栈顺序不能错 ,因为先左后右,
//这样出栈时先遍历才是右(中->右->左)
if (t->left) stk.push(t->left);
if (t->right) stk.push(t->right);
}
reverse(rs.begin(), rs.end()); //逆序,就成了后序遍历了
return rs;
}
};
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<Integer>();
if (root == null) {
return ans;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (!stack.empty()) {
TreeNode n = stack.pop();
ans.add(n.val);
// 注意,下面入栈顺序不能错 ,因为先左后右,
// 这样出栈时先遍历才是右(根.右.左)
if (n.left != null) {
stack.push(n.left);
}
if (n.right != null) {
stack.push(n.right);
}
}
Collections.reverse(ans);
return ans;
}
}