二叉树的建立

二叉树的结构定义:

typedef struct binNode* binTree;
struct binNode
{
	int element;
	binTree leftChild, rightChild;
};

 二叉树的建立:

binTree creatBintree()
{
	int a;
	binTree b;
	scanf("%d", &a);
	
	if (0 == a)	//如果输入0,则停止创建
		b = NULL;
	else
	{
		b = (binTree)malloc(sizeof(struct binNode));
		b->element = a;
		b->leftChild = creatBintree();
		b->rightChild = creatBintree();
		
	}
	return b;
}

二叉树的建立的完整代码。 

#include <stdio.h>
#include <stdlib.h>

typedef struct binNode* binTree;
struct binNode
{
	int element;
	binTree leftChild, rightChild;
};



binTree creatBintree()
{
	int a;
	binTree b;
	scanf("%d", &a);
	
	if (0 == a)	//如果输入0,则停止创建
		b = NULL;
	else
	{
		b = (binTree)malloc(sizeof(struct binNode));
		b->element = a;
		b->leftChild = creatBintree();
		b->rightChild = creatBintree();
		
	}
	return b;
}

void print(binTree b)    //先序遍历
{
	if (b!=NULL)
	{
		printf("%d\n", b->element);
		print(b->leftChild);
		print(b->rightChild);
	}
}

int main(void)
{
	
	binTree bin = creatBintree();
	print(bin);
	return 0;
}

注:这篇文章主要实现二叉树的建立,二叉树的遍历方式将在后续文章中叙述。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二叉树是一种广泛应用于计算机科学中的数据结构,用于存储有层次关系的数据。下面介绍两种建立二叉树的方法。 1. 递归建树 递归建树是一种比较简单的方法,其基本思路是: - 如果当前节点为空,则创建一个新节点并将数据赋值给它; - 如果当前节点不为空,则比较待插入数据和当前节点的大小,如果待插入数据比当前节点小,则递归调用左子树,否则递归调用右子树。 下面是递归建树的示例代码: ```python class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def insert(root, val): if root is None: return TreeNode(val) if val < root.val: root.left = insert(root.left, val) else: root.right = insert(root.right, val) return root ``` 2. 迭代建树 迭代建树是一种较为复杂的方法,需要利用栈来辅助建立二叉树。其基本思路是: - 创建一个空根节点,将待插入数据赋值给根节点; - 从第二个数据开始遍历,对于每个数据,依次与根节点比较大小,如果比根节点小,则作为左子树的根节点,否则作为右子树的根节点; - 使用一个栈来保存访问过的节点,每次访问节点时将其入栈; - 如果当前节点为空,则从栈中弹出一个节点作为当前节点。 下面是迭代建树的示例代码: ```python class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None def insert(root, val): if root is None: return TreeNode(val) stack = [root] while stack: node = stack.pop() if val < node.val: if node.left is None: node.left = TreeNode(val) break else: stack.append(node.left) else: if node.right is None: node.right = TreeNode(val) break else: stack.append(node.right) return root ``` 以上两种方法都可以用于建立二叉搜索树,其中递归建树是更为常见的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值