[Leetcode] 90. 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.

解题之法

class Solution {
public:
    int longestConsecutive(TreeNode* root) {
        if (!root) return 0;
        int res = 0;
        dfs(root, root->val - 1, 0, res);
        return res;
    }
    void dfs(TreeNode *root, int v, int out, int &res) {
        if (!root) return;
        if (root->val == v + 1) ++out;
        else out = 1;
        res = max(res, out);
        dfs(root->left, root->val, out, res);
        dfs(root->right, root->val, out, res);
    }
};

分析

这道题让我们求二叉树的最长连续序列,关于二叉树的题基本都需要遍历树,而递归遍历写起来特别简单,上面这种解法是用到了递归版的先序遍历,我们对于每个遍历到的节点,我们看节点值是否比参数值(父节点值)大1,如果是则长度加1,否则长度重置为1,然后更新结果res,再递归调用左右子节点即可。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容