zoukankan      html  css  js  c++  java
  • lintcode619- Binary Tree Longest Consecutive Sequence III- medium

    It's follow up problem for Binary Tree Longest Consecutive Sequence II

    Given a k-ary tree, find the length of the longest consecutive sequence path.
    The path could be start and end at any node in the tree

    xample

    An example of test data: k-ary tree 5<6<7<>,5<>,8<>>,4<3<>,5<>,3<>>>, denote the following structure:

    
         5
       /   
      6     4
     /|   /|
    7 5 8 3 5 3
    
    Return 5, // 3-4-5-6-7
    

    分治法+全局变量监控。这题只是数据结构改变了,子方法和上面的是一样的。找root+子树的最长increase与最长decrease,加起来-1就是本层的最长root了。

    /**
     * Definition for a multi tree node.
     * public class MultiTreeNode {
     *     int val;
     *     List<TreeNode> children;
     *     MultiTreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        /**
         * @param root the root of k-ary tree
         * @return the length of the longest consecutive sequence path
         */
         
        private int longestConsec = Integer.MIN_VALUE;
        
        private class ResultType {
            int incrs;
            int decrs;
            public ResultType(int incrs, int decrs) {
                this.incrs = incrs;
                this.decrs = decrs;
            }
        }
        
        public int longestConsecutive3(MultiTreeNode root) {
            // Write your code here
            if (root == null) {
                return 0;
            }
            helper(root);
            return longestConsec;
        }
        
        private ResultType helper(MultiTreeNode root) {
            
            List<MultiTreeNode> children = root.children;
            int crtIncrs = 1;
            int crtDecrs = 1;
            
            for (MultiTreeNode child : children) {
                ResultType childResult = helper(child);
                if (root.val + 1 == child.val) {
                    crtIncrs = Math.max(1 + childResult.incrs, crtIncrs);
                }
                if (root.val - 1 == child.val) {
                    crtDecrs = Math.max(1 + childResult.decrs, crtDecrs);
                }
            }
            
            if (crtIncrs + crtDecrs - 1 > longestConsec) {
                longestConsec = crtIncrs + crtDecrs - 1;
            }
            
            return new ResultType(crtIncrs, crtDecrs);
        }
    }
  • 相关阅读:
    Django报错 No module named 'django.templates'
    Django 创建 hello world
    python(Django2.0) 安装
    create-react-app踩坑记
    Vue项目的痛点
    React 错误处理(componentDidCatch)
    Vue props双向绑定
    redux 中的 redux-thunk(中间件)
    webpack 搭建React(手动搭建)
    vue interceptors(拦截器)
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7666076.html
Copyright © 2011-2022 走看看