写递归程序,重要的是四点,输入参数、输出结果、函数的功能、终止条件。
二叉树本身就具有递归这种性质的数据结构,我们需要把它看成“左子树-根节点-右子树”这种结构,就不要再囿于左子节点/右子节点这个思维里了。
/**
* 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 = 0;
public int longestUnivaluePath(TreeNode root) {
if(root==null) return 0;
dfs(root);
return ans;
}
int dfs(TreeNode root){
if(root==null) return 0;
int res = 0;
int l = dfs(root.left);
int r = dfs(root.right);
if(root.left!=null&&root.val==root.left.val
&&root.right!=null&&root.val==root.right.val)
ans = Math.max(ans,r+l+2);
if(root.left!=null&&root.val==root.left.val) res = l + 1;
if(root.right!=null&&root.val==root.right.val) res = Math.max(res,r+1);
ans = Math.max(ans,res);
return res;
}
}