LeetCode之687. Longest Univalue Path

本题目的是在一棵二叉树中寻找彼此连接的连续节点的最长长度,返回连接的边数,提示: 连续节点可经过根节点也可以不经过根节点

思路:
从叶子节点开始寻找左右子节点和本身相同的节点, 若全相同则加1, 使用递归。

C# 代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int LongestUnivaluePath(TreeNode root) 
        {
        int ans = 0;
        findLength(root, ref ans);
        return ans;
        }
        public int findLength(TreeNode root, ref int ans)
        {
            if(root == null) return 0;
            int l = findLength(root.left, ref ans);
            int r = findLength(root.right, ref ans);
            int pl = 0;
            int pr = 0;
            if(root.left != null && root.val == root.left.val)      pl = l+1;
            if(root.right != null && root.val == root.right.val)    pr = r+1;
            ans = Math.Max(ans, pl+pr);
            return Math.Max(pl, pr);

        }
}

python 3代码


猜你喜欢

转载自blog.csdn.net/github_34777264/article/details/80179365