【LeetCode 41】530.二叉搜索树的最小绝对差

【LeetCode 41】530.二叉搜索树的最小绝对差

一、题意

二、思考过程

在对二叉搜索树进行中序遍历的过程中,我们可以直接找到相邻两个节点的差值------用一个 pre节点记录 cur节点的前一个节点。

  • cur:当前节点
  • pre:当前节点的前一个节点

class Solution {
    
    
public:
    int result=INT_MAX;
    TreeNode* pre;
    void traversal(TreeNode* cur)
    {
    
    
        if(cur==NULL) return;
        traversal(cur->left);//左
        if(pre!=NULL)//中
        {
    
    
            result=min(result,cur->val-pre->val);
        }
        pre=cur;//记录前一个节点的指针
        traversal(cur->right);//右
    }

    int getMinimumDifference(TreeNode* root) {
    
    
        traversal(root);
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43891901/article/details/122898799