问题描述
题目描述写一个函数,输入一个二叉树,树中每个节点存放了一个整数值,函数返回这颗二叉树中相差最大的两个节点间的差值绝对值。请注意程序效率。
算法思想
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;
}