783. 二叉搜索树节点最小距离
题目描述
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
输入:root = [4,2,6,1,3]
输出:1
输入:root = [1,0,48,null,null,12,49]
输出:1
递归解答
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int nums=-1;
int min=INT_MAX;
int minDiffInBST(TreeNode* root) {
//中序遍历
if(root->left!=nullptr)minDiffInBST(root->left);
if(nums!=-1&&min>root->val-nums)min=root->val-nums;
nums=root->val;
if(root->right!=nullptr)minDiffInBST(root->right);
return min;
}
};
非递归解答
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDiffInBST(TreeNode* root) {
//中序遍历
stack<TreeNode*> treestack;
TreeNode* cur=root;
int min=INT_MAX;
int num=-1;
while(!treestack.empty()||cur!=nullptr){
while(cur!=nullptr){
treestack.push(cur);
cur=cur->left;
}
cur=treestack.top();
if(num!=-1&&min>cur->val-num){
min=cur->val-num;
}
num=cur->val;
treestack.pop();
cur=cur->right;
}
return min;
}
};
总结
注意关注计算最小值的位置,以及中序遍历的递归和非递归方式的差别。