LeetCode | 687. Longest Univalue Path DFS

Given a binary tree, find the length of the longestpath where each node in the path has the same value. This path may or may notpass through the root.

Note: Thelength of path between two nodes is represented by the number of edges betweenthem.

Example 1:

Input:

              5

             / \

            4   5

           / \   \

          1   1   5

Output:

2

Example 2:

Input:

              1

             / \

            4   5

           / \   \

          4   4   5

Output:

2

Note: Thegiven binary tree has not more than 10000 nodes. The height of the tree is notmore than 1000.

这一题虽然是一道easy题,但是比一般的easy题要难,

这一题使用DFS递归解决,每一个递归点的功能是,在每一个递归点进入的时候,需要传给它从父亲节点到儿子节点一直到当前节点的最大长度,每一个递归点在进入任何一个子树的时候,需要传入父亲节点到儿子节点一直到当前节点的最大长度,在任何一个节点运算完成,返回父节点的时候,需要计算左右节点的返回值之和是否能够更新longpath,然后将左右节点得到的父亲节点到儿子节点一直到当前节点的最大长度中的较长的一个返回上一级

class Solution {
public:
  int P(int &theLongestPath, TreeNode * root,int theLength)
{
	if (root == NULL) return 0;
	int leftCount = 0;
	int rightCount = 0;
	if (root->left!=NULL&& root->left->val == root->val)
	{
		theLongestPath = max(theLength + 1, theLongestPath);
		leftCount=P(theLongestPath, root->left, theLength + 1)+1;
	}
	else
	{
		P(theLongestPath, root->left, 0);
	}
	if (root->right != NULL&&root->right->val == root->val)
	{
		theLongestPath = max(theLength + 1, theLongestPath);
		rightCount=P(theLongestPath, root->right, theLength + 1)+1;
	}
	else
	{
		P(theLongestPath, root->right, 0);
	}
	
	theLongestPath = max(leftCount+rightCount, theLongestPath);
	return max(leftCount, rightCount);
}

int longestUnivaluePath(TreeNode* root) {
	int theLongestPath = 0;
	P(theLongestPath, root, 0);
	return theLongestPath;
}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值