题目:
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.
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.
分析:
给定一颗二叉树,求最长的路径,其中路径是相同节点间的边数。
递归求解此问题,对于每一个结点,我们要求此时最大的路径数,而最大路径数是由其左右两个孩子结点决定的,那么递归的终止条件就是当为空结点时,路径数为0,当我们知道左右孩子的最大路径数时,需要判断当前和左右孩子结点是否相同,如果相同则当前的结点的最大路径数应该为左孩子路径数+1/右孩子路径数+1取最大值,同时更新结果为当前结果和以当前结点根结点时的左右孩子路径数的和的最大值。
程序:
C++
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int longestUnivaluePath(TreeNode* root) { int res = 0; if(root == nullptr) return res; univaluePath(root, res); return res; } private: int univaluePath(TreeNode* root, int& res){ if(root == nullptr) return 0; int l = univaluePath(root->left, res); int r = univaluePath(root->right, res); int pl = 0; int pr = 0; if(root->left != nullptr && root->val == root->left->val) pl = l + 1; if(root->right != nullptr && root->val == root->right->val) pr = r + 1; res = max(res, pl + pr); return max(pl, pr); } };
Java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int longestUnivaluePath(TreeNode root) { if(root == null) return res; univaluePath(root); return res; } private int res = 0; private int univaluePath(TreeNode root){ if(root == null) return 0; int l = univaluePath(root.left); int r = univaluePath(root.right); 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; res = Math.max(res, pl + pr); return Math.max(pl, pr); } }
原文地址:https://www.cnblogs.com/silentteller/p/12353285.html
时间: 2024-10-08 22:50:32