首页 > 解决方案 > 根据输入搜索结构

问题描述

我正在考虑使用二元决策图来实现一个小程序。给定一棵二叉树,按顺序打印其节点。我们根据输入进行分支,例如在这棵树中:二叉树节点有数据、指向左孩子的指针和指向右孩子的指针

我尝试了这种代码,但它不起作用


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; 
} 

标签: c++

解决方案


试试这个功能:

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;:)


推荐阅读