二叉树最长连续序列

二叉树最长连续序列

public class Solution {
    public int max = 1;
    /**
     * @param root: the root of binary tree
     * @return: the length of the longest consecutive sequence path
     */
    public int longestConsecutive(TreeNode root) {
        // write your code here
        if(root == null){
            return 0;
        }
        childNode(root, 1);
        return max;
    }
    
    
    public void childNode(TreeNode node, int n){
        if(node == null){
            return;
        }
        
        if(node.left != null && node.left.val - node.val == 1){
            int left = n + 1;
            max = Math.max(max, left);
            childNode(node.left,left);
        }else{
            childNode(node.left, 1);
        }
        if(node.right != null && node.right.val - node.val == 1){
            int right = n + 1;
            max = Math.max(max, right);
            childNode(node.right,right);
        }else{
            childNode(node.right, 1);
        }
    }
}
复制代码

解题思路:

首先不断下移左右子节点, 如果子节点的val - 父节点的val 等于 1那么说明连续,则节点数加1, 同时比目前的最大节点数max比较,取最大值

文采不好,大家谅解

转载于:https://juejin.im/post/5aed5f916fb9a07ac5600580

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值