美文网首页
[Leetcode] 90. Binary Tree Longe

[Leetcode] 90. Binary Tree Longe

作者: 时光杂货店 | 来源:发表于2017-03-27 18:09 被阅读14次

    题目

    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,再递归调用左右子节点即可。

    相关文章

      网友评论

          本文标题:[Leetcode] 90. Binary Tree Longe

          本文链接:https://www.haomeiwen.com/subject/aairottx.html