问题描述:给出一棵二叉树,返回其节点值的后序遍历。
样例:
给出一棵二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [3,2,1]
实现思路:由二叉树中序遍历的操作定义,用递归算法访问二叉树的节点,并将访问的节点的值存放在向量v中,返回向量v。
实现代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
vector<int> v;
post(v,root);
return v;
}
void post(vector<int> &v,TreeNode *root){
if(root==NULL)
return;
else{
post(v,root->left);
post(v,root->right);
v.push_back(root->val);
}
}
};