leetcode 687最長相同值路徑
阿新 • • 發佈:2019-01-30
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.
/*** Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
int maxpath=0;
if(root==NULL)
{
return 0;
}
countpath(root,root,maxpath);
return maxpath;
}
int countpath(TreeNode *root,TreeNode *root2,int& maxpath)
{
if(root==NULL)
return 0;
int left=countpath(root->left,root,maxpath);
int right=countpath(root->right,root,maxpath);
left=(root->left&&root->left->val==root->val)?left+1:0;
right=(root->right&&root->right->val==root->val)?right+1:0;
maxpath=maxpath>(left+right)?maxpath:(left+right);
return left>right?left:right;
}
};
思路:
對於這種樹的路徑問題,遞迴是不二之選。在遞迴函式中,我們首先對其左右子結點呼叫遞迴函式,得到其左右子樹的最大相同值路徑,下面就要來看當前結點和其左右子結點之間的關係了,如果其左子結點存在且和當前節點值相同,則left自增1,否則left重置0;同理,如果其右子結點存在且和當前節點值相同,則right自增1,否則right重置0。然後用left+right來更新結果res。而呼叫當前節點值的函式只能返回left和right中的較大值,因為如果還要跟父節點組path,就只能在左右子節點中選一條path,當然選值大的那個了