根据二叉树创建字符串

题目:
你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。

空节点则用一对空括号 “()” 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int count;
void tree(struct TreeNode* root, char* str)
{
    if(root){
        count += sprintf(str+count, "%d", root->val );
            if(root->left||root->right){
                count += sprintf(str+count, "%s", "(");
                tree(root->left, str);
                count += sprintf(str+count, "%s", ")");
            }
            if(root->right){
    
               count += sprintf(str+count, "%s", "(");
               tree(root->right, str);
               count += sprintf(str+count, "%s", ")");
            }

    }  
}


char * tree2str(struct TreeNode* t){
    char* str = malloc(50000 );
    count = 0;
    tree(t, str);
    str[count++] = '\0';
    return str; 
}
在C语言中,我们可以使用结构体来表示二叉树节点,每个节点可以包含一个字符串。下面是一个简单的例子: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> // 定义二叉树节点结构体 typedef struct TreeNode { char* str; // 存放字符串的指针 struct TreeNode* left; // 左孩子指针 struct TreeNode* right; // 右孩子指针 } TreeNode; // 插入一个字符串二叉树 void insertIntoBST(TreeNode** root, const char* str) { if (*root == NULL) { *root = (TreeNode*)malloc(sizeof(TreeNode)); (*root)->str = strdup(str); // 深拷贝字符串,防止原始字符串修改影响二叉树 return; } int cmp = strcmp(str, (*root)->str); if (cmp < 0) { insertIntoBST(&(*root)->left, str); } else if (cmp > 0) { insertIntoBST(&(*root)->right, str); } } // 其他辅助函数如查找、删除等 int main() { TreeNode* root = NULL; insertIntoBST(&root, "abc"); insertIntoBST(&root, "def"); insertIntoBST(&root, "ghi"); // 现在你可以遍历这个二叉树,处理字符串 // 示例:按照字典序打印所有字符串 inorderTraversal(root, printf("%s\n", TreeNode::str)); // 假设有一个inorderTraversal函数用于中序遍历 free(root->str); // 注意释放内存 free(root); return 0; } ``` 在这个示例中,我们首先定义了一个`TreeNode`结构体,包含一个指向字符串的指针以及左右孩子的指针。然后实现了插入字符串到二叉搜索树的功能。为了安全地存储字符串,这里用了`strdup`函数创建字符串副本。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值