leetcode687. The longest path with the same value (java)

longest path of equal value

Question description

Difficulty - Medium
LC - 687. Longest path of equal value

Given the root of a binary tree, return the length of the longest path in which every node has the same value. This path may or may not pass through the root node.
The length of the path between two nodes is represented by the number of edges between them.

Example 1:
Insert image description hereInput: root = [5,4,5,1,1,5]
Output: 2

Example 2:
Insert image description hereInput: root = [1,4,5,4,4,5]
Output: 2

Tip:
The range of the number of nodes in the tree is [0, 104]
-1000 <= Node.val <= 1000.
The depth of the tree will not exceed 1000.
Insert image description here

DFS deep traversal

Design the recursive function int dfs(TreeNode root), which means to pass in the root node root and return the maximum path length that can be passed by taking this node as the starting point and going down the path of the same value (that is, you cannot go to the left and right nodes at the same time), and use The global variable max records the maximum path length that the answer path can pass.
Inside the recursive function, first get the maximum path lengths l and r starting from root.left and root.right by recursing the left and right child nodes of the root, and then update ans based on the equality between the current node value and the left and right child node values. , and use cur to maintain the maximum path length "when the current node root is the smallest depth (highest position) node in the target path".

code demo

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    
    int ans;
    public int longestUnivaluePath1(TreeNode root) {
    
    
        ans = 0;
        dfs(root);
        return ans;
    }

    int dfs(TreeNode root){
    
    
        if(root == null){
    
    
            return 0;
        }
        int left = dfs(root.left);
        int right = dfs(root.right);
        //left1 right1 来记录左右节点和头节点的连接情况
         int left1 = 0, right1 = 0;
         //如果左边节点和root 相等,left1 + 1,就连接起来了
        if(root.left != null && root.left.val == root.val){
    
    
            left1 = left + 1;
        }
        //同上
        if(root.right != null && root.right.val == root.val){
    
    
            right1 = right + 1;
        }
        //记录最大值,如果左右节点都相等,两个值相加
        ans = Math.max(ans,left1 + right1);
        return Math.max(left1,right1);
    }
}

Guess you like

Origin blog.csdn.net/SP_1024/article/details/132709207