1. 題目
給你一棵指定的二叉樹,請你計算它最長連續序列路徑的長度。
該路徑,可以是從某個初始結點到樹中任意結點,通過「父 - 子」關係連接而產生的任意路徑。
這個最長連續的路徑,必須從父結點到子結點,反過來是不可以的。
示例 1:
輸入:
1
\
3
/ \
2 4
\
5
輸出: 3
解析: 當中,最長連續序列是 3-4-5,所以返回結果爲 3
示例 2:
輸入:
2
\
3
/
2
/
1
輸出: 2
解析: 當中,最長連續序列是 2-3。注意,不是 3-2-1,所以返回 2。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/binary-tree-longest-consecutive-sequence
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
2. 解題
class Solution {
int maxlen = 1;
public:
int longestConsecutive(TreeNode* root) {
if(!root) return 0;
dfs(root, 1);
return maxlen;
}
void dfs(TreeNode* root, int len)
{
if(!root) return;
maxlen = max(maxlen, len);
if(root->left)
{
if(root->val+1 == root->left->val)
dfs(root->left, len+1);//滿足連續,長度+1
else
dfs(root->left, 1);//不滿足,從新開始
}
if(root->right)
{
if(root->val+1 == root->right->val)
dfs(root->right, len+1);
else
dfs(root->right, 1);
}
}
};
68 ms 33.3 MB
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公衆號(Michael阿明),一起加油、一起學習進步!