算法练习Day17 (Leetcode/Python-二叉树)

513. Find Bottom Left Tree Value

Given the root of a binary tree, return the leftmost value in the last row of the tree.

思路:这题求树的最后一层的最左节点。注意仅仅通过递归求后续遍历的方式找到最左节点是不够的,还要满足在最后一层。所以要选深度最大的最左叶节点。

class Solution(object):
    def findBottomLeftValue(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.max_depth = float('-inf')
        self.result = None
        self.traversal(root, 0)
        return self.result

    def traversal(self,node,depth):
        if not node.left and not node.right:
            if depth > self.max_depth:
                self.max_depth = depth 
                self.result = node.val
            return 
        if node.left:
            depth += 1
            self.traversal(node.left, depth)
            depth -= 1
        if node.right:
            depth += 1
            self.traversal(node.right, depth)
            depth -= 1

530. Minimum Absolute Difference in BST

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

思路:BST 是一个有序的二叉树(左子树所有节点小于其父节点的值,右子树的所有节点的所有值则大雨其父节点的值。左右子树也分别是二叉树。),所以这道题就先按顺序遍历数组,然后两两相邻值相减,最小的差值就是要求的。

class Solution(object):
    def __init__(self):
        self.vec = []  

    def inorder_traversal(self, root): # convert binary search tree to sorted list. 
        if not root:
            return 
        self.inorder_traversal(root.left)
        self.vec.append(root.val)
        self.inorder_traversal(root.right)

    def getMinimumDifference(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.inorder_traversal(root)
        if len(self.vec) < 2:
            return 0
        result = float('inf')
        for i in range(1, len(self.vec)):
            result = min(result, self.vec[i] - self.vec[i-1])
        return result 

化简:

class Solution:
    def __init__(self):
        self.result = float('inf')
        self.pre = None

    def traversal(self, cur):
        if cur is None:
            return
        self.traversal(cur.left)  # 左
        if self.pre is not None:  # 中
            self.result = min(self.result, cur.val - self.pre.val)
        self.pre = cur  # 记录前一个
        self.traversal(cur.right)  # 右

    def getMinimumDifference(self, root):
        self.traversal(root)
        return self.result

迭代法:

class Solution:
    def getMinimumDifference(self, root):
        stack = []
        cur = root
        pre = None
        result = float('inf')

        while cur is not None or len(stack) > 0:
            if cur is not None:
                stack.append(cur)  # 将访问的节点放进栈
                cur = cur.left  # 左
            else:
                cur = stack.pop()
                if pre is not None:  # 中
                    result = min(result, cur.val - pre.val)
                pre = cur
                cur = cur.right  # 右

        return result

你可能感兴趣的:(算法,leetcode,职场和发展)