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]
.
Note: Recursive solution is trivial, could you do it iterativel
题意:后序遍历,不过给出了函数声明,限制了实现方式
思路:采用递归实现。因为函数声明是返回一个vector<int>,所以每个子树返回的是该子树的后序遍历的结果
按照 左、右、根的次序把根和左右子树的vector合并起来就可以了
/** * 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> post; if(root == NULL) return post; TreeNode *left = root->left; TreeNode *right = root->right; if(left) { vector<int> left_vector = postorderTraversal(left); post.insert(post.end(), left_vector.begin(), left_vector.end()); } if(right){ vector<int> right_vector = postorderTraversal(right); post.insert(post.end(), right_vector.begin(), right_vector.end()); } post.push_back(root->val); return post; } };