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

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

Example 1:

Input:

              5
/ \
4 5
/ \ \
1 1 5

Output:

2

Example 2:

Input:

              1
/ \
4 5
/ \ \
4 4 5

Output:

2

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

Runtime: 72 ms, faster than 28.47% of C++ online submissions for Longest Univalue Path.

对于这种不经过root的求和题往往都需要一个临时变量,然后考虑一下根节点和子节点的关系,用一个引用得到最优解。

/**
* 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 ret = , tmpret = ;
helper(root,tmpret, ret);
return ret == ? : ret - ;
}
int helper(TreeNode* root, int& tmpret, int& ret){
if(!root) return ;
int rl = helper(root->left, tmpret, ret);
int rr = helper(root->right, tmpret, ret);
if(!root->left && !root->right) {
tmpret = ;
//ret = 1;
return ;
} else if(!root->left && root->right){
if(root->val == root->right->val){
tmpret = max(tmpret, rr + );
ret = max(ret, tmpret);
return +rr;
} else return ;
} else if(root->left && !root->right){
if(root->val == root->left->val){
tmpret = max(tmpret, +rl);
ret = max(ret, tmpret);
return +rl;
} else return ;
} else {
if(root->val == root->left->val && root->val == root->right->val){
tmpret = max(tmpret, +rr + rl);
ret = max(ret, tmpret);
return +max(rr,rl);
} else if (root->val == root->left->val){
tmpret = max(tmpret, +rl);
ret = max(ret, tmpret);
return +rl;
} else if (root->val == root->right->val){
tmpret = max(tmpret, +rr);
ret = max(ret, tmpret);
return +rr;
} else return ;
}
}
};

最新文章

  1. 文件上传命令rz和下载命令sz的安装
  2. Unicode与JavaScript详解
  3. .net 动态代理的泛型方法支持问题
  4. linux设备驱动归纳总结(五):3.操作硬件——IO静态映射【转】
  5. Elasticsearch内存分配设置详解
  6. java学习笔记(二)之数据部分
  7. 实现在Android开发中的Splash Screen开场屏的效果
  8. iOS-JS交互 (WebViewJavascriptBridge)
  9. bzoj 1924 [Sdoi2010]所驼门王的宝藏(构图,SCC,DP)
  10. Automator 简单使用流程
  11. wndows make images
  12. GDI+ 中发生一般性错误(在 OutputStream 中保存 PNG 格式图像时遇到的问题)
  13. beanutils通过SimpleProperty使用get或set方法赋值
  14. MC 自己平均
  15. Looper Handler Mssage
  16. google ctemplate——c++模板引擎
  17. Firemonkey的几个特色属性(一)
  18. 【第九课】MriaDB密码重置和慢查询日志
  19. 蓝牙设备探测工具blueranger
  20. idea Error:(1, 10) java: 需要class, interface或enum, 未结束的字符串文字,Error:(55, 136) java: 非法字符: \65533

热门文章

  1. 第五篇python进阶之深浅拷贝
  2. Win7系统开机速度慢怎么解决?
  3. 公司 vuessr 项目讲解
  4. 自己实现strcat函数
  5. 更改centos的网卡名
  6. 8张图,让你彻底理解三极管的开关功能 && 經典線路圖
  7. python的方法VSjava方法
  8. 【Python之路】特别篇--Python切片
  9. [winafl]这几天的折腾
  10. luogu 5561 [Celeste-B]Mirror Magic 后缀数组+RMQ+multiset