【问题标题】:Leetcode:Binary Tree Inorder Traversal.problem:Memory Limited exceededLeetcode:二叉树中序遍历问题:超出内存限制
【发布时间】:2018-09-07 01:33:26
【问题描述】:

以下代码执行二叉树中序遍历。当我在 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;
}

【问题讨论】:

标签: binary-tree memory-limit


【解决方案1】:

如果左子节点为空,您的代码只会将值存储到结果堆栈中。

但是,对于您的示例,节点 2 的左子节点永远不会设置为 null,因此它永远不会插入结果堆栈中,而是位于 st 堆栈中。如果您打印输出,您可以观察到 3 被插入到一个循环中,从而导致内存问题。

跟踪祖先的可能策略:

  • 检查琐碎的情况。
  • 准备一个堆栈以保留祖先,并准备一个堆栈以保留结果。
  • 当堆栈非空或根不为空时
    • 如果根不为空:
      • 将根插入祖先堆栈。
      • 将根更新为根的左孩子,可能为空。
    • 如果根为空(意味着从左边开始的死胡同)
      • 访问堆栈,弹出顶部元素作为根。
      • 将根添加到结果堆栈中
      • 将根的右孩子分配为根,可能为空。

【讨论】:

    猜你喜欢
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2019-08-03
    • 2021-12-10
    • 2021-03-08
    • 2020-01-15
    • 1970-01-01
    相关资源
    最近更新 更多