先给出递归版本的实现方法,有时间再弄个循环版的。代码如下:
1 /**
2 * Definition for binary tree
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 vector<int> postorderTraversal(TreeNode *root) {
13 vector<int> nodeValues;
14 if (root == NULL) return nodeValues;
15 postorderTraversal_Rec(root,nodeValues);
16
17 return nodeValues;
18 }
19 private:
20
21 void postorderTraversal_Rec(TreeNode *root, vector<int>& nodeValues){
22 if (root == NULL) return;
23 if (root->left != NULL) postorderTraversal_Rec(root->left,nodeValues);
24 if (root->right != NULL) postorderTraversal_Rec(root->right,nodeValues);
25
26 nodeValues.push_back(root->val);
27 }
28
29 };