File tree 2 files changed +41
-0
lines changed
2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 518
518
684|[ Redundant Connection] ( ./0684-redundant-connection.js ) |Medium|
519
519
685|[ Redundant Connection II] ( ./0685-redundant-connection-ii.js ) |Hard|
520
520
686|[ Repeated String Match] ( ./0686-repeated-string-match.js ) |Easy|
521
+ 687|[ Longest Univalue Path] ( ./0687-longest-univalue-path.js ) |Medium|
521
522
693|[ Binary Number with Alternating Bits] ( ./0693-binary-number-with-alternating-bits.js ) |Easy|
522
523
695|[ Max Area of Island] ( ./0695-max-area-of-island.js ) |Medium|
523
524
696|[ Count Binary Substrings] ( ./0696-count-binary-substrings.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 687. Longest Univalue Path
3
+ * https://leetcode.com/problems/longest-univalue-path/
4
+ * Difficulty: Medium
5
+ *
6
+ * Given the root of a binary tree, return the length of the longest path, where each node
7
+ * in the path has the same value. This path may or may not pass through the root.
8
+ *
9
+ * The length of the path between two nodes is represented by the number of edges between them.
10
+ */
11
+
12
+ /**
13
+ * Definition for a binary tree node.
14
+ * function TreeNode(val, left, right) {
15
+ * this.val = (val===undefined ? 0 : val)
16
+ * this.left = (left===undefined ? null : left)
17
+ * this.right = (right===undefined ? null : right)
18
+ * }
19
+ */
20
+ /**
21
+ * @param {TreeNode } root
22
+ * @return {number }
23
+ */
24
+ var longestUnivaluePath = function ( root ) {
25
+ let max = 0 ;
26
+ dfs ( root ) ;
27
+ return max ;
28
+
29
+ function dfs ( node ) {
30
+ if ( ! node ) return 0 ;
31
+
32
+ const left = dfs ( node . left ) ;
33
+ const right = dfs ( node . right ) ;
34
+ const leftPath = node . left ?. val === node . val ? left + 1 : 0 ;
35
+ const rightPath = node . right ?. val === node . val ? right + 1 : 0 ;
36
+
37
+ max = Math . max ( max , leftPath + rightPath ) ;
38
+ return Math . max ( leftPath , rightPath ) ;
39
+ }
40
+ } ;
You can’t perform that action at this time.
0 commit comments