遍历二叉搜索树,定义一个全局的上一个节点确实好用
/**
* 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 res = 100001;
TreeNode* pre = NULL;
int getMinimumDifference(TreeNode* root) {
tra(root);
return res;
}
void tra(TreeNode* node){
if(!node)return;
tra(node->left);
if(pre!=NULL){
res = min(res,node->val-pre->val);
}
pre = node;
tra(node->right);
}
};
标签:node,right,TreeNode,val,int,随想录,二叉,绝对值,left
From: https://www.cnblogs.com/huigugu/p/18675681