版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hh66__66hh/article/details/83015806
二叉搜索树(BST)——LeetCode783.Minimum Distance Between BST Nodes
题目描述
Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.
Example :
Input: root = [4,2,6,1,3,null,null]
Output: 1
Explanation:
Note that root is a TreeNode object, not an array.
The given tree [4,2,6,1,3,null,null] is represented by the following diagram:
4
/ \
2 6
/ \
1 3
while the minimum difference in this tree is 1, it occurs between node 1 and node 2, also between node 3 and node 2.
Note:
The size of the BST will be between 2 and 100.
The BST is always valid, each node's value is an integer, and each node's value is different.
/**
* 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 minDiffInBST(TreeNode* root) {
}
};
思路
这道题要求给定的二叉搜索树里两个节点数值的最小差。我的思路是得到这个树里的从小到大的排序,最小差肯定是相邻两个数的差值。
要得到从小到大的排序,则先找出二叉搜索树里的最小值,然后从最小值的这个节点开始,依此找出后继节点,并在查找后继节点的过程中算出前后两节点的差值,看是否比当前以获得的最小的差值还小。
这里还要注意,题目给的数据结构中,每个节点没有父节点,所以要预先遍历二叉搜索树,找出每个节点的父节点,存在一个map里。
代码
#include <iostream>
#include <stdio.h>
#include <string>
#include<string.h>
#include <vector>
#include <map>
#include <stack>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;
typedef struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int ans;
map<TreeNode*, TreeNode*>parent;
TreeNode* TreeMinimum(TreeNode* node) {
if(node->left == NULL) {
return node;
}
return TreeMinimum(node->left);
}
TreeNode* Tree_successor(TreeNode* node) {
if(node->right != NULL) {
return TreeMinimum(node->right);
}
TreeNode* p;
TreeNode* n;
if(parent.count(node) == 0) {
p = NULL;
}
else {
p = parent[node];
}
n = node;
while(p!=NULL && p->right==n) {
n = p;
if(parent.count(p) == 0) {
p = NULL;
}
else {
p = parent[p];
}
}
return p;
}
void Find_parent(TreeNode* node) {
if(node->left != NULL) {
parent[node->left] = node;
Find_parent(node->left);
}
if(node->right != NULL) {
parent[node->right] = node;
Find_parent(node->right);
}
}
int minDiffInBST(TreeNode* root) {
parent.clear();
Find_parent(root);
TreeNode* mini = TreeMinimum(root);
TreeNode* temp = mini;
TreeNode* temp2;
ans = 10000000;
int a;
while(temp != NULL) {
temp2 = Tree_successor(temp);
if(temp2 != NULL) {
a = abs(temp2->val-temp->val);
if(ans > a) {
ans = a;
}
}
temp = temp2;
}
return ans;
}
};
int main()
{
TreeNode a(4); TreeNode a1(2); TreeNode a2(6); TreeNode a3(1); TreeNode a4(3);
a.left = &a1; a.right = &a2;
a1.left = &a3; a1.right = &a4;
a2.left = a2.right = NULL;
a3.left = a3.right = NULL;
a4.left = a4.right = NULL;
Solution s;
int ans = s.minDiffInBST(&a);
cout<<ans<<endl;
return 0;
}