leetcode 783. Minimum Distance Between BST Nodes ---中序遍历

Posted wuxiangli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 783. Minimum Distance Between BST Nodes ---中序遍历相关的知识,希望对你有一定的参考价值。

过年晚上无聊,233333333

题解:

BST树的中序遍历是有序的,遍历过程中,记录前一个值,然后和当前值比较,来更新最小的minimum distance

注意python参数传递时候,像list这些object是传引用,单独int的数是传值的

 void getans(TreeNode* root,int &pre,int &ans)
{
    if(root==NULL) return;
    getans(root->left,pre,ans);
    if(pre!=INT_MAX)
        ans=min(ans,abs(pre-root->val));
    pre=root->val;
    getans(root->right,pre,ans);
}
int minDiffInBST(TreeNode* root) {
    int ans=INT_MAX,pre=INT_MAX;
    getans(root,pre,ans);
    return ans;
}

  

import sys
class Solution(object):
    def getans(self,root,pre,ans):
        if root==None:
            return ;
        self.getans(root.left,pre,ans);
        if pre[0]!=sys.maxint:
            ans[0]=min(ans[0],abs(pre[0]-root.val));
        pre[0]=root.val;
        self.getans(root.right,pre,ans);

    def minDiffInBST(self,root):
        """
        :type root: TreeNode
        :rtype: int
        """
        ans=[sys.maxint]
        pre=[sys.maxint]
        self.getans(root,pre,ans)
        return ans[0];

  

以上是关于leetcode 783. Minimum Distance Between BST Nodes ---中序遍历的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 783. 二叉搜索树结点最小距离(Minimum Distance Between BST Nodes)

leetcode 783. Minimum Distance Between BST Nodes ---中序遍历

LWC 71: 783. Minimum Distance Between BST Nodes

783. Minimum Distance Between BST Nodes

783. Minimum Distance Between BST Nodes

783. Minimum Distance Between BST Nodes