获取二叉树的最大节点和最小节点的距离

1、描述

如题:每个节点有一个权值,找到最大权值节点,到最小权值节点的距离,一个算1个

2、关键字

求距离,最大,最小节点

3、思路

首先遍历所有,求出最大和最小的节点,
然后寻找最近的公共父节点,
然后从父节点两个节点的值,相加

6、code


class Tree {
public:
	int minleaf = 100000;
	int maxleaf = 0;
	void getmaxmin(TreeNode * root) {  // 获取最小,最大权值的节点Node,
		if (!root) return;
		if (!root->left && !root->right) {
			if (root->val < minleaf)
				minleaf = root->val;
			if (root->val > maxleaf)
				maxleaf = root->val;
		}
		getmaxmin(root->left);
		getmaxmin(root->right);
	}
	TreeNode * getcommon(TreeNode * root) {  / 获取公共父节点
		if (!root) return nullptr;
		if (root->val == minleaf || root->val == maxleaf) {
			return root;
		}
		auto pL = getcommon(root->left);
		auto pR = getcommon(root->right);
		if (!pL) return pR;
		else if (!pR) return pL;
		else return root;
	}
	int getdist(TreeNode* src, TreeNode * des) {
		if (!src) return -1;
		if (src->val == des->val) return 0;
		int dist = getdist(src->left, des);
		if (dist == -1)
			dist = getdist(src->right, des);
		if (dist != -1)
			return dist + 1;
		return -1;
	}
	int getDis(TreeNode* root) {
		getmaxmin(root);
		auto min = new TreeNode(minleaf);
		auto max = new TreeNode(maxleaf);
		auto com = getcommon(root);
		int minpath = getdist(com, min);
		int maxpath = getdist(com, max);
		return minpath + maxpath;
	}
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值