zoukankan      html  css  js  c++  java
  • leetcode1372

     1 class Solution {
     2     int maxpath = 0;
     3     HashMap<TreeNode, Integer> map1 = new HashMap<TreeNode, Integer>();
     4     HashMap<TreeNode, Integer> map2 = new HashMap<TreeNode, Integer>();
     5 
     6     public void preOrder(TreeNode node) {
     7         if (node != null) {
     8             int leftpath = getTreePath(node, 0, 0);
     9             int rightpath = getTreePath(node, 1, 0);
    10             maxpath = Math.max(maxpath, Math.max(leftpath, rightpath));
    11 
    12             preOrder(node.left);
    13             preOrder(node.right);
    14         }
    15     }
    16 
    17     public int getTreePath(TreeNode node, int direction, int pathsum) {
    18         if (node == null) {
    19             return 0;
    20         } else {
    21             if (direction == 0) {// 向左
    22                 if (map1.containsKey(node)) {
    23                     return pathsum + map1.get(node);
    24                 } else {
    25                     pathsum = getTreePath(node.left, 1, pathsum) + 1;
    26                     map1.put(node, pathsum);
    27                     return pathsum;
    28                 }
    29             } else {// 向右
    30                 if (map2.containsKey(node)) {
    31                     return pathsum + map2.get(node);
    32                 } else {
    33                     pathsum = getTreePath(node.right, 0, pathsum) + 1;
    34                     map2.put(node, pathsum);
    35                     return pathsum;
    36                 }
    37             }
    38         }
    39 
    40     }
    41 
    42     public int longestZigZag(TreeNode root) {
    43         preOrder(root);
    44         return maxpath - 1;
    45     }
    46 }

    算法思路:二叉树遍历+备忘录缓存。

    maxpath记录全局最大的蛇形走位的路径长度,map1记录从某个节点开始左向的最大长度(缓存),map2记录从某个节点开始右向的最大长度(缓存)。

    使用某序遍历整个输,对每一个节点,依次执行左向走法和右向走法,并更新最大全局路径(第10行)。

     注意22行和30行,分别是用缓存加速查询,如果之前已经查询过的节点,就直接返回。

  • 相关阅读:
    CXF JaxWsDynamicClientFactory 错误:编码GBK的不可映射字符
    关于springboot配置DataSource
    Spring Boot2.0加载多个数据源
    Kettle配置发送邮件
    推荐几个不错的VUE UI框架
    vue基础语法一
    Maven在Eclipse下构建多模块项目过程
    利用eclipse把jar包安装到本地仓库
    设计模式之策略模式
    设计模式之观察者模式
  • 原文地址:https://www.cnblogs.com/asenyang/p/12540680.html
Copyright © 2011-2022 走看看