阿里笔试,第二题,在一棵树中找出两个节点,他们的最大值的绝对值是最大的,当时题目没看清楚,以为是编程之美原题,直接把前两天OJ的代码附上。
现给出源代码:
#include<iostream>
using namespace std;
int max = -10000;
int min = 10000;
struct Node
{
int value;
Node *pleft;
Node *pright;
};
Node *CreateTree()//先序遍历初始化二叉树
{
int v = 0;
Node *t = NULL;
if(scanf("%d",&v) == EOF)//EOF即输入ctrl+z时的值,
t = NULL;
else
{
t = (Node *)malloc(sizeof(Node));
t->value = v;
t->pleft = CreateTree();
t->pright = CreateTree();
}
return t;
}
void SearchMaxValue(Node *head)//中序遍历寻找最大值
{
if(head == NULL)
return;
SearchMaxValue(head->pleft);
cout<<head->value<<endl;
if(head->value > max)
max = head->value;
if(head->value < min)
min = head->value;
SearchMaxValue(head->pright);
return;
}
int main()
{
Node *head = CreateTree();
SearchMaxValue(head);//找出最大差值
cout<<max - min<<endl;
return 0;
}
如果用非递归来编译树代码如下:
void NoRecursion_SearchMaxValue(Node *head)
{
stack<Node *> sk;
Node *p = head;
while(p != NULL || !sk.empty())//p有节点,而且有值
{
while(p != NULL)
{
sk.push(p);
p = p->pleft;
}
if(!sk.empty())
{
p = sk.top();
cout<<p->value<<" ";
if(p->value > max)
max = p->value;
if(p->value < min)
min = p->value;
sk.pop();
p = p->pright;
}
}
}