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 11 static int wing=[]() 12 { 13 std::ios::sync_with_stdio(false); 14 cin.tie(NULL); 15 return 0; 16 }(); 17 18 class Solution 19 { 20 public: 21 int res=0; 22 int longestUnivaluePath(TreeNode* root) 23 { 24 if(root==NULL) 25 return 0; 26 count(root); 27 return res; 28 } 29 30 int count(TreeNode* root) 31 { 32 int l=root->left?count(root->left):0; 33 int r=root->right?count(root->right):0; 34 int resl=root->left&&root->left->val==root->val?l+1:0; 35 int resr=root->right&&root->right->val==root->val?r+1:0; 36 res=max(res,resl+resr); 37 return max(resl,resr); 38 } 39 };
这个题要注意一下,容易错,辅助遍历函数有返回值。
原文地址:https://www.cnblogs.com/zhuangbijingdeboke/p/9160621.html
时间: 2024-11-16 00:57:57