145.二叉树的后序遍历
::: caution
原题链接:https://leetcode.cn/problems/binary-tree-postorder-traversal/
:::
思路
根据后序遍历的定义使用递归求解。
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> res;
void dfs(TreeNode* t) {
if (t) {
dfs(t->left);
dfs(t->right);
res.push_back(t->val);
}
}
vector<int> postorderTraversal(TreeNode* root) {
dfs(root);
return res;
}
};