您的位置:首页 > 编程语言

编程之美--求二叉树节点最大距离

2011-09-25 21:50 351 查看
#include<iostream>

#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;

void findMaxLength(Node* root) //编程之美上提供的递归算法

{

if(root==NULL) return;

//如果左子树为空,则该节点左边最长距离为0

if(root->left==NULL)

root->maxLeft=0;

//如果右子树为空,则该节点右边最长距离为0

if(root->right==NULL)

root->maxRight=0;

//如果左子树不为空,递归寻找左边最长距离

if(root->left!=NULL)

findMaxLength(root->left);

//如果右子树不为空,递归寻找右边最长距离

if(root->right!=NULL)

findMaxLength(root->right);

//计算左子树最长节点距离

if(root->left!=NULL)

{

int tempMax=0;

if(root->left->maxLeft > root->left->maxRight)

tempMax=root->left->maxLeft;

else tempMax=root->left->maxRight;

root->maxLeft=tempMax+1;

}

//计算油子树最长节点距离

if(root->right!=NULL)

{

int tempMax=0;

if(root->right->maxLeft > root->right->maxRight)

tempMax=root->right->maxLeft;

else tempMax=root->right->maxRight;

root->maxRight=tempMax+1;

}

//更新最长距离

if(root->maxLeft+root->maxRight > maxLen)

maxLen=root->maxLeft+root->maxRight;

}

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();

}

}

}

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;

findMaxLength(root);

//findMaxLen( root );

cout << maxLen << endl;

system("pause");

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: