c++ - 根据输入搜索结构
问题描述
我正在考虑使用二元决策图来实现一个小程序。给定一棵二叉树,按顺序打印其节点。我们根据输入进行分支,例如在这棵树中:二叉树节点有数据、指向左孩子的指针和指向右孩子的指针
我尝试了这种代码,但它不起作用
include <iostream>
using namespace std;
struct Node
{
int data;
struct Node* left, *right;
Node(int data)
{
this->data = data;
left = right = NULL;
}
};
void printInorder(struct Node* node)
{
printInorder(node->left);
cout << node->data << " ";
printInorder(node->right);
}
int main()
{
struct Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
cout << "\nInorder traversal of binary tree is \n";
printInorder(root);
return 0;
}
解决方案
试试这个功能:
void replace_null(int i, string path, TreeNode* t, string val);
参数i告诉我们下一步在路径中移动的位置。
您可以像这样调用该函数:
replace_null(0, path, t, val);
现在让计算机按照以下路径玩得开心:
void replace_null(int i, string path, TreeNode* t, string val) {
if (path[i] == '1') {
if (t->right == NULL) { // We reached our destination.
add_tree(t->right, val);
return;
}
else { // We continue following the path.
replace_null(i + 1, path, t->right, val);
}
}
else {
if (t->left == NULL) { // We reached our destination.
add_tree(t->left, val);
return;
}
else { // We continue following the path.
replace_null(i + 1, path, t->left, val);
}
}
}
请注意,我确实假设路径总是到达 NULL 节点。否则,if (i == path.size()) return;
:)
推荐阅读
- scala - 我应该在 Spark 2.3.0 中使用 Scala 2.11.0 还是 2.11.8?
- angular - 如何操作`@input` - 有条件地
- python - 检查字符串是否在熊猫数据框中并修改行
- c++ - 从剪辑计算纹理坐标
- paypal - PayPal Checkout - 设置交易送货地址和送货金额
- ios - 在 xcode 中构建我的应用程序时出错..显示未找到架构 x86_64 的符号
- c# - 在 Windows Ce C# 中将字符串转换为 XElement
- flutter - Flutter - 堆栈中定位小部件的效率
- java - Java进程在没有记录的情况下被杀死
- php - 媒体中可下载文件类型的扩展。Drupal 8