《编程之美》读书笔记(十一):“求二叉树中节点的最大距离”扩展问题
感谢azuryy为大家分享《编程之美》第3.8节扩展问题的答案:用非递归的算法求一颗二叉树中相距最远的两个节点之间的距离。
(原博客地址:http://hi.baidu.com/azuryy/blog/item/30ad10ea192424d5d439c96d.html)
#include <stack>
#include <algorithm>
using namespace std;
struct Node
{
bool _visited;
Node* left;
Node* right;
int maxLeft;
int maxRight;
Node()
{
_visited = false;
maxLeft = 0;
maxRight = 0;
left = NULL;
right = NULL;
}
};
int maxLen = 0;
stack<Node*> nodeStack;
void findMaxLen( Node* root )
{
Node* node;
if ( root == NULL )
{
return ;
}
nodeStack.push( root );
while( !nodeStack.empty())
{
node = nodeStack.top();
if ( node->left == NULL && node->right == NULL )
{
nodeStack.pop();
node->_visited = true;
continue;
}
if ( node->left )
{
if ( !node->left->_visited )
{
nodeStack.push( node->left ) ;
}
else
{
node->maxLeft = max( node->left->maxLeft,node->left->maxRight ) + 1;
}
}
if ( ( !node->left || node->left->_visited ) && node->right )
{
if ( !node->right->_visited )
{
nodeStack.push( node->right ) ;
}
else
{
node->maxRight = max( node->right->maxLeft,node->right->maxRight ) + 1;
}
}
if (( !node->left || node->left->_visited ) && ( !node->right || node->right->_visited ))
{
maxLen = max( maxLen, node->maxLeft + node->maxRight );
node->_visited = true;
nodeStack.pop();
}
}
}
Immediate test case 1:
int main()
{
Node *tmp ;
Node* root = new Node();
tmp = new Node();
root->left = tmp ;
tmp = new Node();
root->right = tmp;
tmp = new Node();
root->right->right = tmp;
tmp = new Node();
root->right->right->right = tmp;
tmp = new Node();
root->right->right->right->left = tmp;
findMaxLen( root );
cout << maxLen << endl;
return 0;
}