题目:
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]
.
Note: Recursive solution is trivial, could you do it iteratively?
来源:http://oj.leetcode.com/problems/binary-tree-postorder-traversal/
思路:
常规的递归调用Postorder Traversal。后序遍历顺序是left->right->root
C++ AC代码:
/**
* 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> result;
vector<int> postorderTraversal(TreeNode *root) {
Postorder(root);
return result;
}
void Postorder(TreeNode *root){
if(root!=NULL){
Postorder(root->left);
Postorder(root->right);
result.push_back(root->val);
}
}
};