C ++ implements leetcode687. The longest equal value path

Given a binary tree, find the longest path, and each node in this path has the same value. This path may or may not pass through the root node.

Note: The path length between two nodes is represented by the number of edges between them.
Example 1
Enter:

		5
	       / \
	      4   5
	     / \   \
	    1   1   5

Output:

2

Problem-solving ideas: use recursion

  • Determine whether the current node is empty, or 0 if it is empty

  • If not empty, get the longest equal value path left and right of the left and right sons of the current node

    • Compare the value of the left son with the value of the current node. If equal left = left + 1, set left = 0 if not equal
    • Compare the value of the right son with the value of the current node. If equal right = right + 1, unequal then set right = 0
    • Compare (right + left) with the longest equal-value path, and update the value if it is greater than the longest equal-value path
/**
* 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 sum = 0;    
    int Solve(TreeNode* root){        
	if(root==NULL) return 0;
	int left = Solve(root->left);        
	int right = Solve(root->right);        
	left = (root->left!=NULL && root->left->val==root->val)?left+1:0;        
	right = (root->right!=NULL && root->right->val==root->val)?right+1:0;        
	sum = (right+left)>sum?(right+left):sum;        
	return right>left?right:left;    
    }    
    int longestUnivaluePath(TreeNode* root) {        		   
    	Solve(root);        
    	return sum;    
    }
};
Published 10 original articles · won 9 · visited 1717

Guess you like

Origin blog.csdn.net/weixin_43853811/article/details/105374656