给出一棵二叉树,返回其节点值的后序遍历。
样例
样例 1:
输入:{1,2,3}
输出:[2,3,1]
解释:
1
/ \
2 3
样例 2:
输入:{1,2,#,3,4}
输出:[3,4,2,1]
解释:
1
/
2
/ \
3 4
挑战
你能使用非递归实现么?
注意事项
首个数据为根节点,后面接着是其左儿子和右儿子节点值,"#"表示不存在该子节点。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: A Tree
* @return: Postorder in ArrayList which contains node values.
*/
vector<int> postorderTraversal(TreeNode * root) {
// write your code here
vector<int> res;
recursion(root,res);
return res;
}
void recursion(TreeNode * root, vector<int> &res)
{
if(root)
{
recursion(root->left,res);
recursion(root->right,res);
res.push_back(root->val);
}
}
};