树上最长单色路径

来源:互联网 发布:李刚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
原创粉丝点击