題目描述:
Given a binary tree, return the postorder traversal of its nodes' values.
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
這題就是傳統的tree遍歷,用了傳統的recursion。
Mycode(AC = 10ms):
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Postorder in vector which contains node values.
*/
public:
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
vector<int> ans;
if (root == NULL) return ans;
postorderTraversal(ans, root);
return ans;
}
void postorderTraversal(vector<int>& ans, TreeNode *root) {
if (root == NULL) {
return;
}
// order: left->right->root
postorderTraversal(ans, root->left);
postorderTraversal(ans, root->right);
ans.push_back(root->val);
}
};