我有这样一段代码: (这意味着要在二叉树中找到节点的路径)
vector<TreeNode*> findPath(TreeNode* root, TreeNode *target, vector<TreeNode*> path) {
if (root == target) {
cout << path.size() << endl; // the result is correct here
return path;
}
if (root->left) {
path.push_back(root->left);
findPath(root->left, target, path);
path.erase(path.end()-1);
}
if (root->right) {
path.push_back(root->right);
findPath(root->right, target, path);
path.erase(path.end()-1);
}
}
int main(){
TreeNode *root = new TreeNode(2);
root->left = new TreeNode(1);
vector<TreeNode*> path;
path.push_back(root);
vector<TreeNode*> getPath = findPath(root, root->left, path);
cout << getPath.size() << endl; // here returns an UNEXPECTED value!
}
我的意思是结果在返回之前是正确的。
但是在它返回后,结果是错误的......
我不知道发生了什么。 =(