标签:
求二叉树两个结点的最远距离。
二叉树定义如下:
class TreeNode{ public: int val; TreeNode* left; TreeNode* right; TreeNode(int x):val(x),left(NULL),right(NULL){} };
遍历每个节点,找出以当前节点为根的最长路径,然后找出所有最长路径中的最大值。
代码1:
class Node{ public: int val; Node* left; Node* right; int maxLeft; int maxRight; }; void longestPath_1(Node* pRoot,int& maxLen){ if(pRoot==NULL) return; if(pRoot->left==NULL) pRoot->maxLeft=0; if(pRoot->right==NULL) pRoot->maxRight=0; int leftLen; if(pRoot->left){ longestPath_1(pRoot->left,maxLen); leftLen=1+max(pRoot->left->maxLeft,pRoot->left->maxRight); pRoot->maxLeft=leftLen; } int rightLen; if(pRoot->right){ longestPath_1(pRoot->right,maxLen); rightLen=1+max(pRoot->right->maxLeft,pRoot->right->maxRight); pRoot->maxRight=rightLen; } maxLen=max(pRoot->maxLeft+pRoot->maxRight,maxLen); }
代码2:
class TreeNode{ public: int val; TreeNode* left; TreeNode* right; TreeNode(int x):val(x),left(NULL),right(NULL){} }; void longestPath(TreeNode* pRoot,int& maxLeft,int& maxRight,int& maxLen){ if(pRoot==NULL){ maxLeft=0; maxRight=0; maxLen=0; return; } int maxLeft_1,maxLeft_2,maxRight_1,maxRight_2; longestPath(pRoot->left,maxLeft_1,maxRight_1,maxLen); longestPath(pRoot->right,maxLeft_2,maxRight_2,maxLen); maxLeft=1+max(maxLeft_1,maxRight_1); maxRight=1+max(maxLeft_2,maxRight_2); maxLen=max(maxLeft,maxRight)+1; }
标签:
原文地址:http://www.cnblogs.com/AndyJee/p/4695813.html