摘要:題目解答分治,一種不帶返回值,但需要用全局變量,一種帶返回值,不用全局變量有全局變量
題目:
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 5
Longest consecutive sequence path is 3-4-5, so return 3.
2 3 / 2 / 1
Longest consecutive sequence path is 2-3,not3-2-1, so return 2.
解答:
分治,一種不帶返回值,但需要用全局變量,一種帶返回值,不用全局變量:
1.
//有全局變量 private int max = 0; public void Helper(TreeNode root, int target, int count) { if (root == null) return; if (root.val == target) { count++; } else { count = 1; } max = Math.max(max, count); Helper(root.left, root.val + 1, count); Helper(root.right, root.val + 1, count); } public int longestConsecutive(TreeNode root) { if (root == null) return 0; Helper(root, root.val + 1, 1); return max; }
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)); }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/64903.html
摘要:遞歸法復(fù)雜度時間空間思路因為要找最長的連續(xù)路徑,我們在遍歷樹的時候需要兩個信息,一是目前連起來的路徑有多長,二是目前路徑的上一個節(jié)點的值。代碼判斷當(dāng)前是否連續(xù)返回當(dāng)前長度,左子樹長度,和右子樹長度中較大的那個 Binary Tree Longest Consecutive Sequence Given a binary tree, find the length of the lon...
摘要:題目鏈接這一個類型的題都一樣用,分治的思想。兩種方式一種用,另一種直接把的長度作為返回值,思路都一樣。也可以解,用或者來做,但是本質(zhì)都是。用用返回值在當(dāng)前層處理分別處理左右節(jié)點,這樣不用傳上一次的值,注意這樣初始的就是了 Binary Tree Longest Consecutive Sequence 題目鏈接:https://leetcode.com/problems... 這一個類...
Problem Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree. Especially, this path can be either increasing or decreasing. For example, [1,2,3,4] and [4,3,2,1] ...
摘要:集合法復(fù)雜度時間空間思路將所有數(shù)都加入集合中,然后再遍歷這些數(shù),因為我們能的判斷某個數(shù)是否在集合中,所以我們可以一個個向上或者向下檢查。時間復(fù)雜度仍是,因為我們不會檢查不存在于數(shù)組的數(shù),而存在于數(shù)組的數(shù)也只會檢查一次。 Longest Consecutive Sequence Given an unsorted array of integers, find the length o...
摘要:描述例子要求分析從未排序的數(shù)組中尋找最長的連續(xù)的數(shù)字,必然要循環(huán)一遍所有的數(shù)字,因為連續(xù),所以以出來的數(shù)字為基準(zhǔn),向左右擴散,直到?jīng)]有連續(xù)的,利用了和的特性。 描述: Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 例子: Given ...
閱讀 1318·2021-10-27 14:14
閱讀 3574·2021-09-29 09:34
閱讀 2477·2019-08-30 15:44
閱讀 1716·2019-08-29 17:13
閱讀 2569·2019-08-29 13:07
閱讀 867·2019-08-26 18:26
閱讀 3342·2019-08-26 13:44
閱讀 3210·2019-08-26 13:37