LeetCode 687. Longest Univalue Path(java)

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: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

思路:用递归的方法,思路类似于求binary树的最长路径(可以不通过root),每次都向上返回当前节点的最长路径(在这里就是value相等的最长路径,所以需要对value做判断),然后用一个全局变量来maintain一个max路径的长度。每次向上返回的时候都update一下max值。注意:1. 递归的时候的返回值和maintain的max值是不一样的,如example2中,4节点的update值为2,返回值为1。2. left和right不可以用全局变量来定义,必须每次进入递归的时候reset,否则会干扰,比如先计算完了root.left后,我们有个left值,然后走到root.right的时候,如果left是全局变量,则又会被更新,进而改变了root的返回值。
int max = 0;
    public int longestUnivaluePath(TreeNode root) {
        if (root == null) return 0;
        helper(root);
        return max;
    }
    public int helper(TreeNode root) {
        int left = 0, right = 0;
        if (root == null) return 0;
        if (root.left != null) {
            left = helper(root.left);
        }
        if (root.right != null) {
            right = helper(root.right);
        }
        if (root.left == null && root.right == null) {
            return 0;
        } else if (root.left == null) { 
            if (root.val == root.right.val) {
                int cur = right + 1;
                if (cur > max) max = cur;
                return cur;
            } else {
                return 0;
            }
        } else if (root.right == null) {
            if (root.val == root.left.val) {
                int cur = left + 1;
                if (cur > max) max = cur;
                return cur;
            } else {
                return 0;
            }
        } else if (root.val != root.left.val && root.val != root.right.val) {
            return 0;
        } else if (root.val == root.left.val && root.val == root.right.val) {
            int cur = left + right + 2;
            if (cur > max) max = cur;
            int curr = Math.max(left, right);
            return curr + 1;
        } else if (root.val == root.left.val) {
            int cur = left + 1;
            if (cur > max) max = cur;
            return cur;
        } else {
            int cur = right + 1;
            if (cur > max) max = cur;
            return cur;
        } 
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值