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);
        }
    }
  • 相关阅读:
    python之字典
    Python包管理工具
    【转】Python实现修改Windows CMD命令行输出颜色(完全解析)
    进程池中传递实例方法问题
    HTML协议详解
    【转】python数据格式化之pprint
    【转】Python装饰器与面向切面编程
    【转】TCP/IP报文格式
    python之线程学习
    python之面向对象
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7666076.html
Copyright © 2011-2022 走看看