给你一棵指定的二叉树的根节点 root ,请你计算其中 最长连续序列路径 的长度。
最长连续序列路径 是依次递增 1 的路径。该路径,可以是从某个初始节点到树中任意节点,通过「父 - 子」关系连接而产生的任意路径。且必须从父节点到子节点,反过来是不可以的。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-longest-consecutive-sequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private Info solve(TreeNode root) {
if (root == null) {
return new Info(0, 0);
}
Info left = solve(root.left);
Info right = solve(root.right);
int dp = 1;
if (root.left != null && root.val + 1 == root.left.val) {
dp = Math.max(dp, left.dp + 1);
}
if (root.right != null && root.val + 1 == root.right.val) {
dp = Math.max(dp, right.dp + 1);
}
return new Info(dp, Math.max(dp, Math.max(left.ans, right.ans)));
}
public int longestConsecutive(TreeNode root) {
return solve(root).ans;
}
}
class Info {
int dp;
int ans;
public Info(int dp, int ans) {
this.dp = dp;
this.ans = ans;
}
}
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;
}
}