实验3二叉树的基本操作及应用

二叉树的基本操作及应用
构建如下图二叉树,要求使用括号表示法输入二叉树并转化为二叉树的链式存储结构;横向输出二叉树;查找二叉树中的给定值的结点;求二叉树的高度;统计二叉树中的节点个数;中序遍历该二叉树(采用递归和非递归算法);层序遍历该二叉树;最后编写main函数对以上功能进行测试。

在这里插入图片描述

#include<stdio.h>
#include<malloc.h>
#define MaxSize 100
typedef char ElemType;
typedef char ElemType;
typedef struct node 
{
   	
	ElemType data;			//数据元素
	struct node *lchild;	//指向左孩子结点
	struct node *rchild;	//指向右孩子结点
} BTNode;

void CreateBTNode(BTNode * &b,ElemType *str)
{
   
	BTNode *St[MaxSize],*p=NULL;
	int top=-1,k,j=0;  
	char ch;
	b=NULL;				//建立的二叉树初始时为空
	ch=str[j];
	while (ch!='\0')  	//str未扫描完时循环
	{
   
   	   	switch(ch) 
		{
   
		case '(':top++;St[top]=p;k=1; break;		//为左孩子结点
		case ')':top--;break;
		case ',':k=2; break;                      		//为孩子结点右结点
		default:p=(BTNode *)malloc(sizeof(BTNode));
				p->data=ch;p->lchild=p->rchild=NULL;
				if (b==NULL)                    	 	//*p为二叉树的根结点
					b=p;
				els
  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
构建如下二叉树使用括号表示法输入二叉树转化二叉树链式存储结构,横向输出二叉树,求二叉树的高度,统计二叉树中的节点个数,中序遍历该二叉树(采用递归算法),层序遍历该二叉树的答案如下: ```python # 构建二叉树节点类 class BiTreeNode: def __init__(self, data): self.data = data self.lchild = None self.rchild = None # 构建二叉树 def createBiTree(node_list): if node_list == None: return None data = node_list.pop(0) if data != "#": node = BiTreeNode(data) node.lchild = createBiTree(node_list) node.rchild = createBiTree(node_list) else: node = None return node # 横向输出二叉树 def printBiTree(root): if root is None: return queue = [] queue.append(root) while queue: cur = queue.pop(0) print(cur.data, end=" ") if cur.lchild: queue.append(cur.lchild) if cur.rchild: queue.append(cur.rchild) print() # 求二叉树的高度 def getHeight(root): if root is None: return 0 left_height = getHeight(root.lchild) right_height = getHeight(root.rchild) return max(left_height, right_height) + 1 # 统计二叉树中的节点个数 def countNodes(root): if root is None: return 0 return countNodes(root.lchild) + countNodes(root.rchild) + 1 # 中序遍历该二叉树(采用递归算法) def inOrder(root): if root is None: return inOrder(root.lchild) print(root.data, end=" ") inOrder(root.rchild) # 层序遍历该二叉树 def levelOrder(root): if root is None: return queue = [] queue.append(root) while queue: cur = queue.pop(0) print(cur.data, end=" ") if cur.lchild: queue.append(cur.lchild) if cur.rchild: queue.append(cur.rchild) # 测试代码 if __name__ == '__main__': node_list = ['A', 'B', 'D', '#', '#', 'E', '#', '#', 'C', 'F', '#', '#', 'G', '#', '#'] root = createBiTree(node_list) print("横向输出二叉树:") printBiTree(root) print("二叉树的高度为:", getHeight(root)) print("二叉树的节点个数为:", countNodes(root)) print("中序遍历结果为:", end=" ") inOrder(root) print() print("层序遍历结果为:", end=" ") levelOrder(root) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值