zoukankan      html  css  js  c++  java
  • 298. Binary Tree Longest Consecutive Sequence

    package LeetCode_298
    
    /**
     * 298. Binary Tree Longest Consecutive Sequence (Locked by leetcode)
     * https://www.lintcode.com/problem/binary-tree-longest-consecutive-sequence/description
     * 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-childconnections.
    The longest consecutive path need to be from parent to child (cannot be the reverse).
    
    Example 1:
    Input:
    1
    
    3
    / 
    2  4
    
    5
    Output: 3
    Explanation: Longest consecutive sequence path is 3-4-5, so return 3.
     * */
    
    class TreeNode(var `val`: Int) {
        var left: TreeNode? = null
        var right: TreeNode? = null
    }
    
    class Solution {
        var result = 0
        fun longestConsecutive(root: TreeNode?): Int {
            if (root == null) {
                return 0
            }
            dfs(root, 0, 0)
            return result
        }
    
        /*
       每个遍历到的节点,看节点值是否比参数值(父节点值)大1(因为cannot be the reverse),如果是则长度加1,否则长度重置为1,
       然后更新结果 res,再遍历左右子节点
       */
        private fun dfs(root: TreeNode?, value: Int, current_: Int) {
            if (root == null) {
                return
            }
            var currentLen = current_
            if (root.`val` == value + 1) {
                currentLen++
            } else {
                currentLen = 1
            }
            result = Math.max(currentLen, result)
    
            dfs(root.left, root.`val`, currentLen)
            dfs(root.right, root.`val`, currentLen)
        }
    }
  • 相关阅读:
    nginx申请并配置免费https
    linux安装git
    linux安装openssl
    nginx配置支持http2
    linux服务器升级nginx
    linux 增加虚拟内存swap(使用文件)
    使用shell安装lnmp
    mysql 数据库主从同步
    Android四大组件之Service
    Android四大组件之Activity
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/12861070.html
Copyright © 2011-2022 走看看