LeetCode.687 Longest Univalue Path (經典的求相同節點最長路徑)
阿新 • • 發佈:2019-02-16
題目:
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.
分析:/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { private int max=0; public int longestUnivaluePath(TreeNode root) { //給定二叉樹,找出一條所有節點均為相同值的最長路徑。 //思路:遞迴查詢是否同根節點相同。定義一個全域性變數 //注意:遞迴返回最長的一邊,即單邊最大值 if(root==null) return 0; backtrace(root); return max; } //遞迴 public int backtrace(TreeNode root){ int left=root.left!=null?backtrace(root.left):0; int right=root.right!=null?backtrace(root.right):0; //遞迴判斷是否根節點等於左右 int resLeft=root.left!=null&&root.val==root.left.val?left+1:0; int resRight=root.right!=null&&root.val==root.right.val?right+1:0; max=Math.max(max,resLeft+resRight); //返回最長的一邊 return Math.max(resLeft,resRight); } }