题解 | #二叉树遍历#

二叉树遍历

https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef

#include <stdio.h>
#include <stdlib.h>
typedef char BTDataType;
typedef struct BinaryTreeNode
{
	BTDataType data;
	struct BinaryTreeNode* left;
	struct BinaryTreeNode* right;
}BTNode;
BTNode* BuyNode(BTDataType x)
{
	BTNode* newnode = (BTNode*)malloc(sizeof(BTNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	newnode->data = x;
	newnode->left = NULL;
	newnode->right = NULL;
	return newnode;
}
BTNode* BinaryTreeCreatByString(char* arr, int* i)
{
    if(arr[*i] == '#')
    {
        (*i)++;
        return NULL;
    }
    BTNode* root = BuyNode(arr[*i]);
    (*i)++;
    root->left = BinaryTreeCreatByString(arr, i);
    root->right = BinaryTreeCreatByString(arr, i);
    return root;
    
}
void InOrder(BTNode* root)
{
	if (root == NULL)
	{
		//printf("# ");
		return;
	}
	InOrder(root->left);
	printf("%c ", root->data);
	InOrder(root->right);
}
int main() {
    char arr[100] = {0};
    while(scanf("%s", arr) != EOF)
    {
        int i = 0;
        BTNode* root = BinaryTreeCreatByString(arr, &i);
        InOrder(root);
        printf("\n");
    }
    return 0;
}

全部评论

相关推荐

头像
10-09 19:35
门头沟学院 Java
洛必不可达:java的竞争激烈程度是其他任何岗位的10到20倍
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务