现在有一个二叉树, 父节点保存子节点字符总长度。 typedef struct Node{ char *data; struct Node* left; struct Node* rigth; int length; }Node,*tree; 写一个求substring的功能。 Now, if we call substring with lower idx=2 and upper idx=7, the first part can be fully reused (i.e. "llo"), but the second part "wo" is not an existing cord. Therefore, we would have to create a new cord with this string and then wire that as the blue Cord's right node, as shown in the diagram: 如果子串在整好是在某几个节点上,哪指针直接指在这些节点上,如果此节点上只有部分则需要重新建立新的节点,然后再指向。 求子串的这个函数,返回的还是一个二叉树。如果节点是叶子节点,长度保存的就是字符串的长度。如果节点有子孩子,那么 data就指向空。然后长度是两个孩子里length的和
#include <stdio.h>
#include <stdlib.h>
#include <string.h>typedef struct Node {char *data;struct Node *left;struct Node *right;int length;
} Node, *Tree;// 创建新节点
Node *createNode(char *data, int length) {Node *newNode = (Node *)malloc(sizeof(Node));newNode->data = data;newNode->left = NULL;newNode->right = NULL;newNode->length = length;return newNode;
}// 释放二叉树的内存
void freeTree(Tree root) {if (root == NULL) {return;}freeTree(root->left);freeTree(root->right);if (root->data != NULL) {free(root->data);}free(root);
}// 辅助函数,根据指定范围在字符串中创建新的子串
char *substring(char *str, int lower, int upper) {int len = upper - lower;char *sub = (char *)malloc((len + 1) * sizeof(char));strncpy(sub, str + lower, len);sub[len] = '\0';return sub;
}// 递归函数,根据指定范围在二叉树中查找子串,并返回一个新的二叉树
Tree findSubstring(Tree root, int lower, int upper) {if (root == NULL || lower < 0 || lower >= upper || upper > root->length) {return NULL;}// 如果当前节点保存的字符串刚好是子串的范围,则直接返回该节点if (lower == 0 && upper == root->length) {return root;}// 如果子串在当前节点的左子树中if (lower < root->left->length) {// 如果子串在左子树的末尾if (upper <= root->left->length) {return findSubstring(root->left, lower, upper);}// 子串跨越了左右子树的边界else {char *rightSub = substring(root->data, root->left->length, upper);Node *rightNode = createNode(rightSub, upper - root->left->length);rightNode->right = findSubstring(root->right, 0, upper - root->left->length);return rightNode;}}// 子串在当前节点的右子树中else {return findSubstring(root->right, lower - root->left->length, upper - root->left->length);}
}int main() {// 创建示例二叉树char *data = "Hello, world!";Tree leftChild = createNode("Hello, ", 7);Tree rightChild = createNode("world!", 6);Tree root = createNode(NULL, 13);root->left = leftChild;root->right = rightChild;// 调用findSubstring函数查找子串并返回一个新的二叉树Tree newTree = findSubstring(root, 2, 7);// 打印新的二叉树printf("New tree after substring: %s\n", newTree->data);// 释放内存freeTree(root);free(newTree->data);free(newTree);return 0;
}