二叉树中最大最小权值节点距离问题

#include <iostream>
#include <vector>
#include <map>
#include <queue>
using namespace std;

const int a[] = { 4, 1, 0, 0, 7, 0, 0 };
int index = 0;
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
		val(x), left(NULL), right(NULL) {
	}
};

void CreatTree(TreeNode** T)
{
	int value;

	//cout << "please input the value\n";
	//cin >> value;
	value = a[index++];
	if (value == 0)
		*T = NULL;
	else
	{		
		*T = new TreeNode(value);
		CreatTree(&(*T)->left);
		CreatTree(&(*T)->right);
	}
};
void Inorder(TreeNode *root, vector<int>&v, int &small, int &big){
		//中序遍历获得最小的叶节点和最大的叶节点的索引
		if (!root)
			return;
		Inorder(root->left, v, small, big);
		v.push_back(root->val);
		if (root->left == NULL&&root->right == NULL){//叶子节点
			if (small == -1 || big == -1)
				small = big = (int)v.size() - 1;
			else{
				if (root->val<v[small]) small = (int)v.size() - 1;
				if (root->val>v[big])   big = (int)v.size() - 1;
			}
		}
		Inorder(root->right, v, small, big);
	}
int getDis(TreeNode* root) {
		int small = -1, big = -1;
		vector<int>v;
		Inorder(root, v, small, big);
		TreeNode * p = root;
		vector<int>v1, v2;
		int pos;
		while (true) {//寻找路径
			pos = (int)(find(v.begin(), v.end(), p->val) - v.begin());
			v1.push_back(v[pos]);
			if (small>pos)
				p = p->right;
			else if (small<pos)
				p = p->left;
			else
				break;
		}
		p = root;
		while (true) {
			pos = (int)(find(v.begin(), v.end(), p->val) - v.begin());
			v2.push_back(v[pos]);
			if (big>pos)
				p = p->right;
			else if (big<pos)
				p = p->left;
			else
				break;
		}
		int i, j;
		for (i = 0, j = 0; j<v2.size() - 1 && i<v1.size() - 1; ++i, ++j) {//去重
			if (!(v1[i] == v2[j] && v1[i + 1] == v2[j + 1]))
				break;
		}
		return (int)v1.size() - 1 + (int)v2.size() - 1 - 2 * i;
}

int main()
{
	
	TreeNode* T = nullptr;
	CreatTree(&T);
	cout << getDis(T);



}

posted @ 2016-03-31 18:46  牧羊少年10号  阅读(243)  评论(0编辑  收藏  举报