【发布时间】:2018-10-22 12:41:11
【问题描述】:
我正在做一些 LeetCode 问题(LeetCode 的新问题),并且我编写了一个用于迭代遍历二叉树的解决方案。我使用了一个堆栈,我相信我的逻辑是有效的,但是 LeetCode 给了我一个运行时错误。我怎样才能解决这个问题?
这是我的代码:
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
TreeNode* temp = root;
vector<int> v;
stack<TreeNode*> s;
if (temp == NULL)
return v;
while (true){
while (temp != NULL){
if (temp->right)
s.push(temp->right);
s.push(temp);
temp = temp->left;
}
if (s.empty())
break;
temp = s.top();
s.pop();
if (s.top() == temp->right){
s.pop();
s.push(temp);
temp = temp->right;
}else{
v.push_back(temp->val);
temp = NULL;
}
}
return v;
}
};
请帮忙,谢谢!
【问题讨论】:
-
@albusSimba 他问的是迭代方法而不是递归
-
我正在编辑我的评论
-
@GaneshChowdharySadanala 已编辑!但不能解决运行时错误
-
@Ruby 我只是询问了有关该方法的更多信息,而不是解决方案
-
@Ruby 在下面查看我的代码,不要忘记接受它,这会让我们继续前进
标签: c++ iteration traversal postorder