下面的代码按照顺序执行二进制树遍历。当我在Leetcode中执行它时,我会收到一个Run Status Code: Memory Limit Exceeded。有人能解释一下是什么导致了这个错误吗?
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL)
return res;
stack<TreeNode*> st;
st.push(root);
while(st.empty()==0){
TreeNode* cur=st.top();
st.pop();
if(cur->right!=NULL)//right childtree is not NULL,push
st.push(cur->right);
if(cur->left!=NULL){//left childtree is not NULL,push
st.push(cur);
st.push(cur->left);
}
else //if left child tree is NULL,store the value
res.push_back(cur->val);
}
//inorder(root,res);
return res;
}

发布于 2018-09-07 02:41:04
如果左子节点为null,则代码仅将值存储到结果堆栈中。
但是,对于您的示例,节点2左子节点从未设置为null,因此它从未插入结果堆栈,而是插入到st堆栈中。如果打印出输出,您可以观察到3被插入到一个循环中,从而导致内存问题。
跟踪祖先的可能策略:
- if the root is null (meaning dead end from the left)
- visit the stack, pop the top element to be the root.
- add the root to the result stack
- assign the right child of the root to be the root, possibly to be a null.
https://stackoverflow.com/questions/52214129
复制相似问题