687. Longest Univalue Path
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
Note: The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5
/ \
4 5
/ \ \
1 1 5
Output:
2
Example 2:
Input:
1
/ \
4 5
/ \ \
4 4 5
Output:
2
Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
找出相同节点相连的路径,求最长的边数和
C++(71ms):
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int longestUnivaluePath(TreeNode* root) { 13 int res = 0 ; 14 if (root) 15 dfs(root , res) ; 16 return res ; 17 18 } 19 20 int dfs(TreeNode* root , int& res){ 21 int l = root->left ? dfs(root->left , res) : 0 ; 22 int r = root->right ? dfs(root->right , res) : 0 ; 23 24 int leftEdge = (root->left && root->left->val == root->val) ? l + 1 : 0 ; 25 int rightEdge = (root->right && root->right->val == root->val) ? r + 1 : 0 ; 26 res = max(res , leftEdge + rightEdge) ; 27 return max(leftEdge , rightEdge) ; 28 } 29 };