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>ans;
postorder(root,ans);
return ans;
}
void postorder(TreeNode* root,vector<int>&ans)
{
if (root==NULL) return ;
if (root->left) postorder(root->left,ans);
if (root->right) postorder(root->right,ans);
ans.push_back(root->val);
}
};