具体思想:
自底向上,其实不太用修改;
自己傻傻的修改了,不过总体思想和自己想的一样;
具体代码:
1.自己版本:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int longestUnivaluePath(TreeNode* root) {
if(!root){
return 0;
}
int ret=0;
fun(root,ret);
return ret;
}
void fun(TreeNode* root,int& maxn){
if(!root)
return;
if(root->val!=nof){
cntleaf(root, root->val, maxn);
}
fun(root->left,maxn);
fun(root->right,maxn);
}
int cntleaf(TreeNode* root,int val,int& maxn){
if(!root||root->val!=val){
return 0;
}
root->val=nof;
int left=cntleaf(root->left,val,maxn);
int right=cntleaf(root->right,val,maxn);
maxn=max(left+right,maxn);
return max(left,right)+1;
}
private:
const int nof=1100;
};
2.官方题解版本:
class Solution {
int ans;
public int longestUnivaluePath(TreeNode root) {
ans = 0;
arrowLength(root);
return ans;
}
public int arrowLength(TreeNode node) {
if (node == null) return 0;
int left = arrowLength(node.left);
int right = arrowLength(node.right);
int arrowLeft = 0, arrowRight = 0;
if (node.left != null && node.left.val == node.val) {
arrowLeft += left + 1;
}
if (node.right != null && node.right.val == node.val) {
arrowRight += right + 1;
}
ans = Math.max(ans, arrowLeft + arrowRight);
return Math.max(arrowLeft, arrowRight);
}
}