Binary Tree Longest Consecutive Sequence

本文介绍了一种算法,用于寻找二叉树中最长的连续节点路径,并通过递归方式实现。该算法采用深度优先搜索策略,利用全局变量记录并返回最长路径的长度。

Given the root of a binary tree, return 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 needs to be from parent to child (cannot be the reverse).

Example 1:

Input: root = [1,null,3,2,4,null,null,null,5]
Output: 3
Explanation: Longest consecutive sequence path is 3-4-5, so return 3.

Example 2:

Input: root = [2,null,3,2,null,1]
Output: 2
Explanation: Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.

Constraints:

  • The number of nodes in the tree is in the range [1, 3 * 104].
  • -3 * 104 <= Node.val <= 3 * 104

思路:traverse the whole tree, 全局变量记录count的最大值,同时传递parent null,如果cur.val = parent.val + 1; count++,否则count = 1;

也就是说,往上传递的是参数 count,也就是是否consequence的information;全局的变量记录最大值,如果不连续,往上面传1,否则传递count++; 记得返回的不是以函数值return,而是以参数为返回上一层;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int longestConsecutive(TreeNode root) {
        int[] res = new int[]{0};
        dfs(root, res);
        return res[0];
    }
    
    private int dfs(TreeNode root, int[] res) {
        if(root == null) {
            return 0;
        }    
        int leftdepth = dfs(root.left, res);
        int rightdepth = dfs(root.right, res);
        int localdepth = 1;
        if(root.left != null) {
            if(root.val + 1 == root.left.val) {
                localdepth = Math.max(localdepth, leftdepth + 1);
            }
        }
        if(root.right != null) {
            if(root.val + 1 == root.right.val) {
                localdepth = Math.max(localdepth, rightdepth + 1);
            }
        }
        res[0] = Math.max(res[0], localdepth);
        return localdepth;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值