【发布时间】:2022-01-11 09:06:38
【问题描述】:
我是 C++ 的初学者,正在尝试编写一个程序来跟踪二叉树的两个节点之间的路径。
上面给出了路径跟踪的示例。 我已经编写了一个程序来执行如下所示:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
};
void getPosition(TreeNode* root, int Value, vector<bool> &list, bool *found) {
if(root == NULL) {
return;
}
if(root->val == Value) {
*found = true;
return;
}
cout<<root->val;
getPosition(root->left, Value, list, found);
if(*found) {
list.push_back(true);
return;
}
getPosition(root->right, Value, list, found);
if(*found) {
list.push_back(false);
return;
}
return;
}
string getDirections(TreeNode* root, int startValue, int destValue) {
string Answer;
vector<bool> start;
vector<bool> end; //left = true and right = false;
bool *condition;
*condition = false;
getPosition(root, startValue, start, condition);
*condition = false;
getPosition(root, destValue, end, condition);
int S_size = start.size();
int E_size = end.size();
for(int i=0;i<S_size;i++) {
cout<<start[i]<<"A";
}
int i=0;
if(S_size == 0) {
for(int e = E_size - 1;e>=0;e--) {
if(end[e] == true) {
Answer.append("R");
}
else {
Answer.append("L");
}
}
return Answer;
}
if(E_size == 0) {
for(int s = 0;s<S_size;s++) {
Answer.append("U");
}
return Answer;
}
while(true) {
if(start[S_size - i - 1] == end[E_size - i - 1]) {
i++;
}
else break;
}
for(int s = 0;s<S_size - i;s++) {
Answer.append("U");
}
for(int e = E_size - i - 1;e>=0;e--) {
if(end[e] == true) {
Answer.append("R");
}
else {
Answer.append("L");
}
}
return Answer;
}
int main() {
TreeNode* root = new TreeNode;
root->val = 5;
root->left = new TreeNode;
root->left->val = 1;
root->left->left = new TreeNode;
root->left->left->val = 3;
root->right = new TreeNode;
root->right->val = 2;
root->right->left = new TreeNode;
root->right->left->val = 6;
root->right->right = new TreeNode;
root->right->right->val = 4;
cout<<root->right->right->val;
string s = getDirections(root, 3, 6);
cout<<s;
return 0;
}
我试图查明程序不工作的地方,发现在函数getPosition 中,if(root == NULL) 的条件没有得到评估。
谁能告诉我为什么这不起作用?
谢谢
【问题讨论】:
-
bool *condition; *condition = false;ingetDirections是未定义的行为。condition未初始化为指向任何内容,因此尝试写入*condition没有任何意义。也许你的意思是bool condition = false; getPosition(root, StartValue, start, &condition)? -
@NathanPierson 我试着按照你说的做,但它仍然没有解决为什么它不进入 root == NULL 条件的问题。感谢您的评论。
-
在 C++ 中,使用
nullptr而不是NULL。 -
如果
condition是true,则可能要在从getPosition返回后签入getDirections,如果不是,则返回(未找到节点)。 -
@LaxmanChinannavar -- 我试过照你说的做,但还是没解决问题 -- 这不是解决问题的问题。您的代码是错误的,所指出的只是其中一件毫无疑问是错误的事情。这不是您只需要“尝试”的东西,如果您要继续解决问题,它是您必须更改的代码。
标签: c++ function tree binary-tree