298. Binary Tree Longest Consecutive Sequence
生活随笔
收集整理的這篇文章主要介紹了
298. Binary Tree Longest Consecutive Sequence
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
Given a binary tree, find the length of the longest consecutive sequence path.
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).
For example,
1\3/ \2 4\5Longest consecutive sequence path is 3-4-5, so return 3.
2\3/ 2 / 1Longest consecutive sequence path is 2-3,not3-2-1, so return 2.
解答:
分治,一種不帶返回值,但需要用全局變量,一種帶返回值,不用全局變量:
1.
2.
public int Helper(TreeNode root, int target, int count) {if (root == null) return 1;count = root.val == target ? count + 1 : 1;int left = Helper(root.left, root.val + 1, count);int right = Helper(root.right, root.val + 1, count);return Math.max(Math.max(left, right), count); }public int longestConsecutive(TreeNode root) {if (root == null) return 0;return Math.max(Helper(root.left, root.val + 1, 1), Helper(root.right, root.val + 1, 1)); }總結
以上是生活随笔為你收集整理的298. Binary Tree Longest Consecutive Sequence的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mcmod模组下载脚本
- 下一篇: MinGW - Minimalist G