C++ recursive method


  • 0
    X
       int find(int left, int right, int value, vector<int>& vec){
            while(left <= right){
                if(vec[left] == value){
                    return left;
                }
                ++left;
            }
            return -1;
        }
        TreeNode* recur(int il, int ir, int pl, int pr, vector<int>& inorder, vector<int>& postorder){
            if(il > ir){
                return NULL;
            }else if(il == ir){
                return new TreeNode(inorder[il]);
            }
            int idx = find(il, ir, postorder[pr], inorder);
            TreeNode* root = new TreeNode(postorder[pr]);
            root->left = recur(il, idx - 1, pl, pl + idx - il - 1, inorder, postorder);
            root->right = recur(idx + 1, ir, pl + idx - il, pr - 1, inorder, postorder);
            return root;
        }
        TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
            return recur(0, inorder.size() - 1, 0, postorder.size() - 1, inorder, postorder);
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.