难度:Hard
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]
.
代码如下:
static void visit(TreeNode * p,vector<int>&VEC)
{
VEC.push_back(p->val);
}
void posttraverse(TreeNode * p,void visit(TreeNode * ,vector<int>&),vector<int>&VEC)
{
if(p==NULL)
{
return ;
}
posttraverse(p->left,visit,VEC);
posttraverse(p->right,visit,VEC);
visit(p,VEC);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int>result;
posttraverse(root,&visit,result);
return result;
}
比较需要注意的是void类型的函数不能在普通函数体内直接使用,而是要在声明的时候声明成static的状态,要不然就无法使用visit函数。