二叉树最长连续序列

二叉树最长连续序列

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于一棵二叉树,我们可以定义其最长上升子序列(LIS)为从根节点开始,沿着任意路径向下遍历,使得经过的结点值单调递增的最长路径长度。 为了求解二叉树的 LIS,可以考虑使用动态规划(DP)的方法。具体来说,我们可以定义一个数组 dp,其中 dp[i] 表示以第 i 个结点为结尾的 LIS 长度。对于一个结点 i,其 LIS 长度可以通过枚举其所有子结点 j,如果 val[i] < val[j],则有转移方程: dp[i] = max(dp[i], dp[j] + 1) 最终的 LIS 长度即为 dp 数组中的最大值。 下面是一个 Python 代码实现: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def longest_increasing_path(root: TreeNode) -> int: def dfs(node: TreeNode) -> Tuple[int, int]: if not node: return 0, 0 left_len, left_inc = dfs(node.left) right_len, right_inc = dfs(node.right) cur_len = 1 if node.left and node.left.val > node.val: cur_len = max(cur_len, left_inc + 1) if node.right and node.right.val > node.val: cur_len = max(cur_len, right_inc + 1) cur_inc = 1 if node.left and node.left.val < node.val: cur_inc = max(cur_inc, left_len + 1) if node.right and node.right.val < node.val: cur_inc = max(cur_inc, right_len + 1) return cur_len, cur_inc return dfs(root)[0] ``` 其中 dfs 函数返回一个元组,第一个元素表示以当前结点为结尾的 LIS 长度,第二个元素表示以当前结点为结尾的 LIS 递减子序列长度。对于每个结点,我们分别计算其向左子树和右子树的 LIS 长度和递减子序列长度,并根据当前结点与子结点之间的大小关系来更新当前结点的 LIS 长度和递减子序列长度。最终返回根节点的 LIS 长度即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值