码迷,mamicode.com
首页 > 其他好文 > 详细

【树】687. 最长同值路径

时间:2020-05-03 16:30:10      阅读:38      评论:0      收藏:0      [点我收藏+]

标签:int   col   图片   info   mic   alt   pre   mamicode   nullptr   

题目:

技术图片

 

 

 

解答:

技术图片

 

 技术图片

 

 

 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 help(TreeNode* node, int &ans)
13     {
14         if (node == nullptr) 
15         {
16             return 0;
17         }
18 
19         int left = help(node->left, ans);
20         int right = help(node->right, ans);
21 
22         left = (node->left != nullptr && node->val == node->left->val) ? left + 1 : 0;
23         right = (node->right != nullptr && node->val == node->right->val) ? right + 1 : 0;
24 
25         ans = max(ans, left + right);
26         return max(left, right);
27     }
28 
29     int longestUnivaluePath(TreeNode* root)
30     {
31         int ans = 0;
32         help(root, ans);
33         return ans;
34     }
35 
36 };

 

【树】687. 最长同值路径

标签:int   col   图片   info   mic   alt   pre   mamicode   nullptr   

原文地址:https://www.cnblogs.com/ocpc/p/12822119.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!