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

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);
}
};
上一篇:数组方法slice()把类数组转成数组和复制一个数组


下一篇:Python 精进版SVIP版通过队列实现一个生产者消费者模型