为什么需要将 rootIdx 作为地址传递?

问题描述

这是一个 leetcode 问题“Construct Binary Tree from Preorder and Inorder Traversal”,在这解决方案中,我想知道为什么我们传递了“int rootIdx = 0;”作为地址,如果我只是按值传递它,为什么我的代码会失败。

class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder,vector<int>& inorder) {
        int rootIdx = 0;
        return build(preorder,inorder,rootIdx,inorder.size()-1);
    }
    
    TreeNode* build(vector<int>& preorder,vector<int>& inorder,int& rootIdx,int left,int right) {
        if (left > right) return NULL;
        int pivot = left;  // find the root from inorder
        while(inorder[pivot] != preorder[rootIdx]) pivot++;
        
        rootIdx++;
        TreeNode* newNode = new TreeNode(inorder[pivot]);
        newNode->left = build(preorder,left,pivot-1);
        newNode->right = build(preorder,pivot+1,right);
        return newNode;
    }
};

谢谢你

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)