File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode id=687 lang=javascript
3
+ *
4
+ * [687] Longest Univalue Path
5
+ */
6
+
7
+ // 返回经过root的且只能取左右一个节点的路径长度
8
+ function helper ( node , res ) {
9
+ if ( node === null ) return 0 ;
10
+ const l = helper ( node . left , res ) ;
11
+ const r = helper ( node . right , res ) ;
12
+ let lcnt = 0 ;
13
+ let rcnt = 0 ;
14
+ if ( node . left && node . val === node . left . val ) lcnt = lcnt + l + 1 ;
15
+ if ( node . right && node . val === node . right . val ) rcnt = rcnt + r + 1 ;
16
+
17
+ res . max = Math . max ( res . max , lcnt + rcnt ) ;
18
+
19
+ return Math . max ( lcnt , rcnt ) ;
20
+ }
21
+ /**
22
+ * Definition for a binary tree node.
23
+ * function TreeNode(val) {
24
+ * this.val = val;
25
+ * this.left = this.right = null;
26
+ * }
27
+ */
28
+ /**
29
+ * @param {TreeNode } root
30
+ * @return {number }
31
+ */
32
+ var longestUnivaluePath = function ( root ) {
33
+ const res = {
34
+ max : 0
35
+ } ;
36
+ helper ( root , res ) ;
37
+ return res . max ;
38
+ } ;
You can’t perform that action at this time.
0 commit comments