Minimum Absolute Difference in BST
2017-02-26 16:07
337 查看
leectcode第530题,竞赛题的签到题,比赛居然不会做。。。
主要是基本的数据结构还不熟,这里要求求一个二叉搜索树节点直接数值绝对差的最小值。注意,节点间是指所有节点之间,不是相邻节点之间。
这里很明显要用到二叉搜索树的一个性质,那就是二叉搜索树中序遍历会得到一个有序数组,这样一来,绝对值差肯定是这个数组相邻两个数的差里面的最小值了。
主要是基本的数据结构还不熟,这里要求求一个二叉搜索树节点直接数值绝对差的最小值。注意,节点间是指所有节点之间,不是相邻节点之间。
这里很明显要用到二叉搜索树的一个性质,那就是二叉搜索树中序遍历会得到一个有序数组,这样一来,绝对值差肯定是这个数组相邻两个数的差里面的最小值了。
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def getMinimumDifference(self, root): """ :type root: TreeNode :rtype: int """ def inOreder(node, nodeList): if node.left != None: inOreder(node.left, nodeList) nodeList.append(node.val) if node.right != None: inOreder(node.right, nodeList) nodeList = [] inOreder(root, nodeList) n = len(nodeList) absDiff = [] for i in range(n-1): absDiff.append(nodeList[i+1]-nodeList[i]) return min(absDiff)
相关文章推荐
- leetcode-Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST问题及解法
- leetcode Minimum Absolute Difference in BST 二叉搜索树中的最小差
- Leetcode 530 Minimum Absolute Difference in BST
- leetcode[Minimum Absolute Difference in BST]//待整理多种解法
- Minimum Absolute Difference in BST
- LeetCode 530 Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- LeetCode Minimum Absolute Difference in BST
- [LeetCode] Minimum Absolute Difference in BST 二叉搜索树的最小绝对差
- Minimum Absolute Difference in BST
- Leetcode Minimum Absolute Difference in BST
- LC-Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- Minimum Absolute Difference in BST
- LeetCode 530 Minimum Absolute Difference in BST(BST中序遍历)
- No.530 Minimum Absolute Difference in BST
- Leetcode #530 Minimum Absolute Difference in BST