您的位置:首页 > 产品设计 > UI/UE

[leetcode] 298. Binary Tree Longest Consecutive Sequence 解题报告

2016-03-14 05:44 513 查看
题目链接: https://leetcode.com/problems/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
\
5

Longest consecutive sequence path is
3-4-5
,
so return
3
.
2
\
3
/
2
/
1

Longest consecutive sequence path is
2-3
,not
3-2-1
,
so return
2
.

思路: 比较基础的一个DFS, 维护一个当前的连续长度和一个全局最大长度, 每一个往左右子树搜索的时候看是不是正好大一, 然后更新两个变量.

代码如下:

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void DFS(TreeNode* root, int pre, int len, int& Max)
{
if(!root) return;
len = (root->val==pre+1)?len+1:1;
Max = max(Max, len);
DFS(root->left, root->val, len, Max);
DFS(root->right, root->val, len, Max);
}

int longestConsecutive(TreeNode* root) {
if(!root) return 0;
int Max = 1;
DFS(root, root->val, 0, Max);
return Max;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: