ALBB 二叉树中相差最大节点的绝对差值

问题描述

题目描述写一个函数,输入一个二叉树,树中每个节点存放了一个整数值,函数返回这颗二叉树中相差最大的两个节点间的差值绝对值。请注意程序效率。

算法思想

1、先序遍历二叉树,求得最大值、最小值即求得最终的绝对值差值;

源码实现(TNode)

#include<iostream>
#include<stdio.h>

using namespace std;

typedef struct TNode
{
	int data;
	TNode* lc;
	TNode* rc;
}TNode;

void CreatBiT(TNode *root)
{	
	int data;
	cin>>data;
	while(data!=0)
	{
		root->data = data;
		root->lc =  new TNode;
		root->rc =  new TNode;
		CreatBiT(root->lc);
		CreatBiT(root->rc);
		return;
	}
	root->data = NULL;
	return;
}
void PreOrd(TNode *root,int *max,int *min)
{
	if(root->data!=NULL)
	{
		int data = root->data;
		if(*max<data)
			*max=data;
		if(*min>data)
			*min=data;
		PreOrd(root->lc,max,min);
		PreOrd(root->rc,max,min);
	}
	else
		return;

}
int main()
{
	TNode *root = new TNode;
	CreatBiT(root);
	int max = root->data;
	int min = root->data;
	PreOrd(root,&max,&min);
	cout<<max-min<<endl;
	return 0;
}

源码实现(TNode*)

#include<stdio.h>  
#include <stdlib.h>  
  
typedef struct Node {  
    int data;  
    struct Node * left;  
    struct Node * right;  
} BitNode, *BiTree;  
  
/* 求差值的函数,传入一个二叉树,其中 *min, *max 初始放 root-data, *value 放差值即要求的值 */  
void getValue(BiTree bt, int *min, int *max, int* value) {  
    if(bt == NULL) return;  
    if (*min > bt->data) *min = bt->data;  
    if (*max < bt->data) *max = bt->data;  
    *value = *max - *min;  
    getValue(bt->left, min, max, value);  
    getValue(bt->right, min, max, value);  
}  
  
void CreateTree(BiTree *bt, int a[], int len, int index) {  
    if (index > len - 1) return;  
    (*bt) = (BiTree) malloc(sizeof(BitNode));  
    (*bt)->data = a[index];  
    (*bt)->left = NULL;  
    (*bt)->right = NULL;  
    CreateTree(&((*bt)->left), a, len, 2 * index + 1);  
    CreateTree(&((*bt)->right), a, len, 2 * index + 2);  
}  
  
/* 两个小测试 */  
int main() {  
    int arr[] = { 0, 1, -9, 3, 4, 5, 6, 7};  
    int arr2[] = { 0, 1, -9, 3, 10};  
    BiTree root, root2;  
    CreateTree(&root, arr, sizeof(arr) / sizeof(int), 0);  
    CreateTree(&root2, arr2, sizeof(arr2) / sizeof(int), 0);  
    int a, max = root->data, min = root->data;  
    int a2, max2 = root2->data, min2 = root2->data;  
    getValue(root, &max, &min, &a);  
    getValue(root2, &max2, &min2, &a2);  
    printf("%d, %d",a,a2);  
    return 0;  
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值