Write a function, enter a binary tree, each node in the tree holds an integer value, and the function returns the absolute value of the difference between the two nodes in the binary tree with the largest difference. Please note program efficiency
This is a 2015 Arichu strokes of an online pen question
The implementation method is very simple, traverse the binary tree, find the maximum minimum, one subtraction can find the maximum difference
Before doing the problem is actually write recursive method evaluation, after testing a bit, and sure enough the result is wrong
As long as the non-recursive method traversal can easily find the maximum minimum value, the efficiency is relatively high, the time complexity of O (n).
Here's how I traverse a binary tree with a non-recursive top down
Can be easily implemented with a queue container.
I wrote the code:
#include <iostream>
#include <tchar.h>
#include <queue>
using namespace Std;
typedef struct BINARYTREENODE
{
int m_nvalue;
Binarytreenode *m_pleft;
Binarytreenode *m_pright;
}binarytreenode;
int Maxt (Binarytreenode *proot)
{
int max=proot->m_nvalue,min=proot->m_nvalue;
if (!proot)
{
return 0;
}
queue<binarytreenode*>qtree;
Qtree.push (Proot);
while (!qtree.empty ())
{
Binarytreenode *pnode=qtree.front ();
if (Max<pnode->m_nvalue)
{
max=pnode->m_nvalue;
}
Else
if (Min>pnode->m_nvalue)
{
min=pnode->m_nvalue;
}
Qtree.pop ();
if (pnode->m_pleft)
Qtree.push (Pnode->m_pleft);
if (pnode->m_pright)
Qtree.push (Pnode->m_pright);
}
return max-min;
}
Build a binary tree in the first order, and enter 1 to indicate that the node is empty.
void Createbinarytree (Binarytreenode *&proot)
{
int nnodevalue = 0;
Cin >> Nnodevalue;
if ( -1== nnodevalue)
{
Proot = NULL;
Return
}
Else
{
Proot = new Binarytreenode ();
Proot->m_nvalue = Nnodevalue;
Createbinarytree (Proot->m_pleft);
Createbinarytree (Proot->m_pright);
}
}
void Printinorder (Binarytreenode *&proot)
{
if (proot! = NULL)
{
Printinorder (Proot->m_pleft);
cout << proot->m_nvalue << "";
Printinorder (Proot->m_pright);
}
}
int _tmain (int argc, _tchar* argv[])
{
Binarytreenode *proot = NULL;
Createbinarytree (Proot);
cout << "Middle sequence traversal as:" <<endl;
Printinorder (Proot);
cout << Endl;
int Maxabs=maxt (proot);
cout<< "Maximum absolute value" <<maxabs<<endl;
Vector<int> path;
Findpath (proot, n, Path);
System ("pause");
return 0;
}
2015 Arichu strokes one of the algorithm questions (classic)