https://leetcode.com/problems/longest-univalue-path/

1. Use recursion:

  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 result = 0;
  14. arrowLength(root, result);
  15. return result;
  16. }
  17. private:
  18. int arrowLength(TreeNode* root, int& result){
  19. if(!root) return 0;
  20. int l_path = arrowLength(root->left, result);
  21. int r_path = arrowLength(root->right, result);
  22. int arrowLeft = 0, arrowRight = 0;
  23. if(root->left && root->left->val == root->val)
  24. arrowLeft = arrowLeft + l_path + 1;
  25. if(root->right && root->right->val == root->val)
  26. arrowRight = arrowRight + r_path + 1;
  27. result = max(result, arrowLeft + arrowRight);
  28. return max(arrowLeft, arrowRight);
  29. }
  30. };