LeetCode 687. Longest Univalue Path — JavaScript Solution

今天學習了拉花,真的超困難!
var longestUnivaluePath = function(root) {
if (!root) return 0;
return Math.max(
longestPassPath(root.left, root.val) + longestPassPath(root.right, root.val),
longestUnivaluePath(root.left),
longestUnivaluePath(root.right)
)
};
const longestPassPath = (root, val) => {
if (!root || root.val !== val) return 0;
const left = longestPassPath(root.left, val);
const right = longestPassPath(root.right, val);
return 1 + Math.max(left, right)
};

題目意思是判斷最長相同的 node,因此只要分別判斷中間跟左右以及左右子樹等三種狀態。

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
黃韋智

自學寫程式,目前爲 React 前端工程師。熱愛旅遊,將近 30 個國家,足跡遍佈亞洲與歐洲。生命與街舞已經離不開,歡迎訂閱 Youtube 頻道:https://www.youtube.com/channel/UCEU-bEDl7R-iGyLVZFae33g