(二叉树 递归) leetcode 145. Binary Tree Postorder Traversal

时间:2021-08-10 16:50:52

Given a binary tree, return the postorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
1
\
2
/
3 Output: [3,2,1]

Follow up: Recursive solution is trivial, could you do it iteratively?

---------------------------------------------------------------------------------------------------------------------

leetcode 144. Binary Tree Preorder Traversal类似。

emmm,这个题是hard难度题,大概是在迭代上是不好写吧,不过递归是很容易写的。

C++代码:

/**
* Definition for a binary tree node.
* 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> vec;
postorder(root,vec);
return vec;
}
void postorder(TreeNode *root,vector<int> &vec){
if(!root) return;
postorder(root->left,vec);
postorder(root->right,vec);
vec.push_back(root->val);
}
};