先给出递归版本的实现方法,有时间再弄个循环版的。代码如下:
/**
* Definition for binary tree
* 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> nodeValues;
if (root == NULL) return nodeValues;
postorderTraversal_Rec(root,nodeValues); return nodeValues;
}
private: void postorderTraversal_Rec(TreeNode *root, vector<int>& nodeValues){
if (root == NULL) return;
if (root->left != NULL) postorderTraversal_Rec(root->left,nodeValues);
if (root->right != NULL) postorderTraversal_Rec(root->right,nodeValues); nodeValues.push_back(root->val);
} };