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

来源:互联网 发布:战舰世界岛风f3雷数据 编辑:程序博客网 时间:2024/05/25 18:09

题目链接: 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,not3-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;    }};


0 0
原创粉丝点击