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).

题目其实不难,但是这个题不太好想,因为涉及到断点拼接的问题比如 1, 2 和 4, 5, 6

需要两个量来记录,一个是全局的总长度,一个是局部的长度。

java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */


public class Solution {
    /*
     * @param root: the root of binary tree
     * @return: the length of the longest consecutive sequence path
     */
    int longth = 0;
    public int longestConsecutive(TreeNode root) {
        // write your code here
        findLongth(root);
        return longth;
    }
    private int findLongth(TreeNode root) {
        int line = 1;
        if (root == null) {
            return 0;
        }
        int left = findLongth(root.left);
        int right = findLongth(root.right);
        
        if (root.left != null && root.val + 1 == root.left.val) {
            line = Math.max(line, left + 1);
        }
        if (root.right != null && root.val + 1 == root.right.val) {
            line = Math.max(line, right + 1);
        }
        if (line > longth) {
            longth = line;
        }
        return line;
    }
}
python

class Solution:
    """
    @param: root: the root of binary tree
    @return: the length of the longest consecutive sequence path
    """
    Longest = 0
    def longestConsecutive(self, root):
        # write your code here
        self.findLong(root)
        return self.Longest
    def findLong(self, root):
        if root is None:
            return 0
        line = 1
        left = self.findLong(root.left)
        right = self.findLong(root.right)
        if root.left is not None and root.val + 1 == root.left.val:
            line = max(left + 1, line)
        if root.right is not None and root.val + 1 == root.right.val:
            line = max(right + 1, line)
        if line > self.Longest:
            self.Longest = line
        return line
        



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ncst

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值