Longest Univalue Path问题及解法

问题描述:

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.

示例:

Input:

              5
             / \
            4   5
           / \   \
          1   1   5

Output:

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.
 * 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 = 1;
		queue<TreeNode *> que;
		if (root == nullptr) return 0;
		que.push(root);
		while (!que.empty())
		{
			int size = que.size();
			for (int i = 0; i < size; i++)
			{
				TreeNode * r = que.front();
				que.pop();
				if (r->left) que.push(r->left);
				if (r->right) que.push(r->right);
				int re = bl(r->left,r->val) + bl(r->right,r->val) + 1;
				if (res < re) res = re;
			}
		}
		return res - 1;
	}

	int bl(TreeNode* root,int val)
	{
		if (root == nullptr || root->val != val) return 0;
		int left = bl(root->left, val);
		int right = bl(root->right, val);
		return max(left, right) + 1;
	}
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值