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

来源:互联网 发布:淘宝手机端详情页gif 编辑:程序博客网 时间:2024/06/07 18:14
#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;elsebreak;}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;elsebreak;}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);}

0 0
原创粉丝点击