https://leetcode.com/problems/longest-univalue-path/
1. Use recursion:
/*** 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 result = 0;arrowLength(root, result);return result;}private:int arrowLength(TreeNode* root, int& result){if(!root) return 0;int l_path = arrowLength(root->left, result);int r_path = arrowLength(root->right, result);int arrowLeft = 0, arrowRight = 0;if(root->left && root->left->val == root->val)arrowLeft = arrowLeft + l_path + 1;if(root->right && root->right->val == root->val)arrowRight = arrowRight + r_path + 1;result = max(result, arrowLeft + arrowRight);return max(arrowLeft, arrowRight);}};
