过年晚上无聊,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];