//145. 二叉树的后序遍历
//正常递归实现,比较简单
class Solution {
public:
vector<int> ans;
void dfs(TreeNode* node) {
if (node == nullptr) return;
dfs(node->left);
dfs(node->right);
ans.emplace_back(node->val);
}
vector<int> postorderTraversal(TreeNode* root) {
dfs(root);
return ans;
}
};
//使用stack,有点绕,建议多想想,手动狗头
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int>ans;
if (root == nullptr) return ans;
auto node = root;
stack<TreeNode*> stk;
TreeNode* ptr;
while (node != nullptr || stk.size()) {
while (node != nullptr) {
stk.push(node);
node = node->left;
}
node = stk.top(); stk.pop();
if (node->right == nullptr || node->right == ptr) {
ans.emplace_back(node->val);
ptr = node;
node = nullptr;
}
else {
stk.emplace(node);
node = node->right;
}
}
return ans;
}
};
LeetCode145. 二叉树的后序遍历
最新推荐文章于 2022-04-17 19:38:10 发布