Leetcode 算法题17



530Minimum Absolute Difference in BST

找出二叉树中每两个节点的值之差的最小值

Example:

Input:

   1
    \
     3
    /
   2

Output:
1

Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
我的代码:没想到什么好办法,枚举出所有值进行排序对比

# 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
        """
        list_ = []
        stack = [root]
        while stack:
            node = stack.pop()
            if node:
                list_.append(node.val)
            if node.left:stack.append(node.left)
            if node.right:stack.append(node.right)
        list_.sort()
        ans = list(map(lambda x,y:abs(x-y),list_[1:]+[list_[0]],list_))
        return min(ans)
大神的代码:对二叉搜索树进行完整的排序

def getMinimumDifference(self, root):
        def dfs(node, l=[]):
            if node.left: dfs(node.left, l)
            l.append(node.val)
            if node.right: dfs(node.right, l)
            return l
        l = dfs(root)   #如果不是BST,则需要排序
        return min([abs(a-b) for a,b in zip(l, l[1:])])
这个一行排序更厉害
class Solution(object):
    def getMinimumDifference(self, root):
        nums = self.inorder(root)
        return min(nums[i+1]-nums[i] for i in range(len(nums)-1))
        
    def inorder(self, root):
        return self.inorder(root.left) + [root.val] + self.inorder(root.right) if root else []

100 Same Tree

判断两个树是否一样

530Minimum Absolute Difference in BST

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false
我的代码:

# 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 isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if not p and not q:
            return True
        elif not(p and q):
            return False
        if p.val != q.val:
            return False
        else:
            if (p.left and q.left) and (p.right and q.right):
                return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
            elif (p.left and q.left) and (not p.right and not q.right):
                return self.isSameTree(p.left,q.left)
            elif (p.right and q.right) and (not p.left and not q.left):
                return self.isSameTree(p.right,q.right)
            elif (not p.left and not q.left) and (not p.right and not q.right):
                return True
            else:
                return False   

大神的代码:只能说膜拜..

The “proper” way:

def isSameTree(self, p, q):
    if p and q:
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
    return p is q

The “tupleify” way:

def isSameTree(self, p, q):
    def t(n):
        return n and (n.val, t(n.left), t(n.right))
    return t(p) == t(q)

The first way as one-liner:

def isSameTree(self, p, q):
    return p and q and p.val == q.val and all(map(self.isSameTree, (p.left, p.right), (q.left, q.right))) or p is q


563Binary Tree Tilt

计算所有节点的Tilt之和,Tilt指这个节点的所有左边子子节值和所有右边子子节值之差

Example:

Input: 
         1
       /   \
      2     3
Output: 1
Explanation: 
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
我的代码:关于这种树的我写得都好长,喜欢用BFS
# 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 findTilt(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def calcSum(n):
            ans = 0
            if not n:
                return 0
            stack = [n]
            while stack:
                node = stack.pop()
                if node:
                    ans += node.val
                if node.left:stack.append(node.left)
                if node.right:stack.append(node.right)
            return ans
        def calcTilt(n):
            if not n:
                return 0
            return abs(calcSum(n.left) - calcSum(n.right))
        stack_ = [root]
        sum_ = 0
        while stack_:
            node_ = stack_.pop()
            if node_:
                sum_ += calcTilt(node_)
                if node_.left:stack_.append(node_.left)
                if node_.right:stack_.append(node_.right)
        return sum_
大神的代码:感觉和树有关的很多很好的办法都用递归

def findTilt(self, root):
        def tilt(root):
            # return (sum, tilt) of tree
            if not root: return (0, 0)
            left = tilt(root.left)
            right = tilt(root.right)
            return (left[0] + right[0] + root.val, abs(left[0] - right[0]) + left[1] + right[1])
        return tilt(root)[1]
这段代码让我觉得我完全没摸到递归的门路,我的代码会重复计算很多子节的和,这种避免了重复

def findTilt(self, root):
    self.ans = 0
    def _sum(node):
        if not node: return 0
        left, right = _sum(node.left), _sum(node.right)
        self.ans += abs(left - right)
        return node.val + left + right
    _sum(root)
    return self.ans
继续大神的代码:

def findTilt(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        def csum(root):
            if not root:
                return 0
            return root.val+csum(root.left)+csum(root.right)
        return abs(csum(root.left)-csum(root.right))+self.findTilt(root.left)+self.findTilt(root.right)


671Second Minimum Node In a Binary Tree

求整个二叉树中第二小的数,ac后看了别人的代码才发现题目没看完全,这个树每个节点要么有2个子节点要么没有子节点,而且子节点的值必定比节点值大

Example 1:

Input: 
    2
   / \
  2   5
     / \
    5   7

Output: 5
Explanation: The smallest value is 2, the second smallest value is 5.

Example 2:

Input: 
    2
   / \
  2   2

Output: -1
Explanation: The smallest value is 2, but there isn't any second smallest value.

我的代码:

# 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 findSecondMinimumValue(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return -1
        stack = [root]
        nums = set()
        while stack:
            node = stack.pop()
            if node:
                nums.add(node.val)
                if node.left:stack.append(node.left)
                if node.right:stack.append(node.right)
        nums.remove(min(nums))
        return min(nums) if nums else -1
大神的代码:我发现这个叫awice的人很厉害

Say the value of the root is min1. If some node’s value is larger, it might be the answer, but every descendant node will be at least as big, so we don’t need to check them.

def findSecondMinimumValue(self, root):
    self.ans = float('inf')  #float('inf')表示正无穷
    min1 = root.val

    def dfs(node):
        if node:
            if min1 < node.val < self.ans:
                self.ans = node.val
            elif node.val == min1:
                dfs(node.left)
                dfs(node.right)

    dfs(root)
    return self.ans if self.ans < float('inf') else -1
还有一个叫Yangshun的,不过他的还没上面的好

class Solution(object):
    def findSecondMinimumValue(self, root):
        res = [float('inf')]
        def traverse(node):
            if not node:
                return
            if root.val < node.val < res[0]:
                res[0] = node.val
            traverse(node.left)
            traverse(node.right)
        traverse(root)
        return -1 if res[0] == float('inf') else res[0]
482 License Key Formatting

按要求转化字符

Input: S = "5F3Z-2e-9-w", K = 4

Output: "5F3Z-2E9W"

Explanation: The string S has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.

Example 2:

Input: S = "2-5g-3-J", K = 2

Output: "2-5G-3J"

Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be sh
我的代码:

class Solution(object):
    def licenseKeyFormatting(self, S, K):
        """
        :type S: str
        :type K: int
        :rtype: str
        """
        S = ''.join(re.split(r'\-',S)).upper()
        ans = ''
        count = 0
        for i in S[::-1]:
            if count % K != 0:
                ans = i + ans
            else:
                ans = i + '-' + ans
            count += 1
        return ans.strip('-')
其他代码:都是按着顺序来,否者会有超时

class Solution(object):
    def licenseKeyFormatting(self, S, K):
        """
        :type S: str
        :type K: int
        :rtype: str
        """
        S = S.upper().replace('-','')
        size = len(S)
        s1 = K if size%K==0 else size%K
        res = S[:s1]
        while s1<size:
            res += '-'+S[s1:s1+K]
            s1 += K
        return res
有个正则表达式的:
class Solution(object):
    def licenseKeyFormatting(self, S, K):
        """
        :type S: str
        :type K: int
        :rtype: str
        """
        formatted = S.replace("-","",len(S)).upper()[::-1]
        formatted = re.sub(r'(\\w{' + str(K) + r'})', r'\\1-', formatted)
        formatted = formatted[::-1]
        formatted = re.sub(r'^-',r'', formatted)
        return formatted




530 Minimum Absolute Difference in BST
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值