publicintdfs(TreeNode root, int val) { if (root == null) return0; intleft= dfs(root.left, root.val), right = dfs(root.right, root.val); ans = Math.max(ans, left + right); return root.val == val ? Math.max(left, right) + 1 : 0; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Code language: C++ classSolution { public: int ans = 0; intlongestUnivaluePath(TreeNode* root){ dfs(root, -1); return ans; }
intdfs(TreeNode* root, int val){ if (root == nullptr) return0; int left = dfs(root->left, root->val), right = dfs(root->right, root->val); ans = max(ans, left + right); return root->val == val ? max(left, right) + 1 : 0; } };
1 2 3 4 5 6 7 8 9 10 11 12
/* Code language: JavaScript */ var longestUnivaluePath = function(root) { let ans = 0; const dfs = function(root, val) { if (root == undefined) return0; const left = dfs(root.left, root.val), right = dfs(root.right, root.val); ans = Math.max(ans, left + right); return root.val == val ? Math.max(left, right) + 1 : 0; }; dfs(root, -1); return ans; };