树上最长单色路径
来源:互联网 发布:李刚java疯狂讲义 pdf 编辑:程序博客网 时间:2024/04/26 15:31
对于一棵由黑白点组成的二叉树,我们需要找到其中最长的单色简单路径,其中简单路径的定义是从树上的某点开始沿树边走不重复的点到树上的另一点结束而形成的路径,而路径的长度就是经过的点的数量(包括起点和终点)。而这里我们所说的单色路径自然就是只经过一种颜色的点的路径。你需要找到这棵树上最长的单色路径。
给定一棵二叉树的根节点(树的点数小于等于300,请做到O(n)的复杂度),请返回最长单色路径的长度。这里的节点颜色由点上的权值表示,权值为1的是黑点,为0的是白点。
import java.util.*;/*public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}*/public class LongestPath { public final static int MAXN = 305; public final static int WHITE = 0; public final static int BLACK = 1; // dp[i]为经过第i个根节点的最长单色路径 private int dp[][] = new int[MAXN << 2][2]; private int ans=0; private void init() { for (int i = 0, n = dp.length; i < n; i++) { for (int j = 0, m = dp[i].length; j < m; j++) { dp[i][j] = -1; } } } private void DFS(TreeNode root, int root_id) { if (dp[root_id][WHITE] != -1 || dp[root_id][BLACK] != -1) return; if (root == null) { dp[root_id][WHITE] = dp[root_id][BLACK] = 0; return; } DFS(root.left, root_id << 1); DFS(root.right, root_id << 1 | 1); // 包含本节点的最长路径至少为0 dp[root_id][WHITE] = dp[root_id][BLACK] = 0; if (root.val == WHITE) { dp[root_id][WHITE] = Math.max(dp[root_id << 1][WHITE], dp[root_id << 1 | 1][WHITE]) + 1; //若左右节点和根节点同色,最长的路径应该是从左子树到右子树 ans = Math.max(ans, dp[root_id << 1][WHITE] + dp[root_id << 1 | 1][WHITE] + 1); } else { dp[root_id][BLACK] = Math.max(dp[root_id << 1][BLACK], dp[root_id << 1 | 1][BLACK]) + 1; ans = Math.max(ans, dp[root_id << 1][BLACK] + dp[root_id << 1 | 1][BLACK] + 1); } } public int findPath(TreeNode root) { init(); DFS(root, 1); return ans; }}
0 0
- 树上最长单色路径
- 树上最长单色路径
- 树上最长单色路径
- 树上最长单色路径
- 二叉树上最长单色路径
- [编程题]树上最长单色路径
- 一站通offer 树上最长单色路径
- [编程题]树上最长单色路径
- 深度优先 树上最长单色路径
- nowcoder 树上最长单色路径(最长路径,二叉树+dp)
- 获取最长单色子路径的长度
- 二叉树单色路径最长&&穿珠子
- hdu2196 Computer(树上最长路径 dp)
- UVa 10308 - Roads in the North (树上的最长路径)
- CarrerCup-多叉树上的最长连续路径
- HDU_2196_Computer(树上节点的最长路径 · dfs / bfs)
- CSU oj 1681 Adjoin(dfs求树上最长路径)
- 树上路径
- 第一个开源控件:Google官方下拉刷新控件SwipeRefreshLayout强化版,支持上拉刷新
- Visualizations&plot&pivot_table
- 协议理解,包括接口等
- Opera 开发者版本推出VPN功能【分享】
- ubuntu16.04使用手札(一)——WingIDE安装
- 树上最长单色路径
- 基于android的Socket通信
- struts2中的constant配置详解
- 网页简介及个人理解
- mysql性能优化
- 跨平台的一般的高质量数据传输方法理论
- Memcached真的过时了吗
- Git版本控制使用方法入门教程
- tomcat6.0