二叉树中的结点间距离:从结点A出发到达B,每个结点只能走一次,AB路径上的边数就是AB间距离。
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int GetMaxDistance(TreeNode *root) {
int maxDistance = numeric_limits<int>::min();
GetMaxDistance(root, maxDistance);
return maxDistance;
}
private:
int GetMaxDistance(TreeNode *node, int &maxDistance) {
if (node == nullptr)
return -1;
int leftMaxDepth = GetMaxDistance(node->left, maxDistance);
int rightMaxDepth = GetMaxDistance(node->right, maxDistance);
int tempDistance = leftMaxDepth + rightMaxDepth + 2;
if (tempDistance > maxDistance)
maxDistance = tempDistance;
return 1 + max(leftMaxDepth, rightMaxDepth);
}
};