Given a binary tree, find the length of the longest consecutive sequence path.node
The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path need to be from parent to child (cannot be the reverse).this
Example 1:spa
Input: 1 \ 3 / \ 2 4 \ 5 Output: Explanation: Longest consecutive sequence path is , so return .33-4-53
Example 2:code
Input: 2 \ 3 / 2 / 1 Output: 2 Explanation: Longest consecutive sequence path is , not , so return .2-33-2-12
class Solution { private int maxLength = 0; public int longestConsecutive(TreeNode root) { helper(root); return maxLength; } private int helper(TreeNode root){ if(root == null){ return 0; } // 拿 左邊和右邊的 值 int left = helper(root.left); int right = helper(root.right); // 決定當前的值 應該什麼, 當前的 值 和 左邊 的 , 還有 右邊的 值 都有關係 if(root.left != null && root.left.val == root.val + 1){ left = left + 1; // 若是能夠加的上 }else{ left = 1; // 加不上 } if(root.right != null && root.right.val == root.val + 1){ right = right + 1; // same as above }else{ right = 1; } int length = Math.max(left, right); // 返回 單方向的 一條 path 值 maxLength = Math.max(length, maxLength); // update global max return length; // 帶返回值的recursion } } // time : o(n), space, o(height) // this is smiliar to another problem similar to this one, in a way that // when you wonder , what if the result is actually starting from some nodes in the middle // because 當你往上傳值得時候, 下面的全部的狀況已經計算好了, 也是按照這個recursion 的 步驟 進行的, // 這道題和 那個 max paths sum from any node to any node 像, 由於 最後答案中的 root 能夠是 任何一個 node。 // 因此 這個題 就是 以每一個 node 爲 root 的 結果 都要探索一遍。 這兩個好像都是從下往上傳的值, // Input: // 1 // \ // 3 // / \ // 2 4 // \ // 5 // Output: 3 // Explanation: Longest consecutive sequence path is 3-4-5, so return 3.