美文网首页
687. Longest Univalue Path

687. Longest Univalue Path

作者: 冷殇弦 | 来源:发表于2017-10-03 02:53 被阅读0次

    Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
    Note: The length of path between two nodes is represented by the number of edges between them.
    Example 1:

    Input:
    5
    /
    4 5
    / \
    1 1 5

    Output:
    2

    Example 2:

    Input:
    1
    /
    4 5
    / \
    4 4 5

    Output:
    2

    Note:

    1. The given binary tree has not more than 10000 nodes.
    2. The height of the tree is not more than 1000.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        
        int longest = 0;
        public int longestUnivaluePath(TreeNode root) {
            traverse(root);
            return longest;
        }
        public int traverse(TreeNode node){
            if(node==null) return 0;
            int l=traverse(node.left);
            int r=traverse(node.right);
            int left = (node.left!=null && node.left.val==node.val)? l+1:0;
            int right = (node.right!=null && node.right.val==node.val)? r+1:0;
            longest = Math.max(longest,left + right);
            return Math.max(left,right);
        }
    }
    

    相关文章

      网友评论

          本文标题:687. Longest Univalue Path

          本文链接:https://www.haomeiwen.com/subject/hgjxyxtx.html