leetcode 515

此题想要找到树中每一行的最大值,采用递归的方式去做。在子问题合并的时候依次遍历list,将更大的那个值保留下来,由于左右子树可能不等高,所以需要把更高的那个子树剩下的值在加进去,有点像排序时合并的操作。

代码如下:

# 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 largestValues(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        result = []
        if root == None:
            return []
        if root.left == None and root.right == None:
            return [root.val]
        elif root.left == None:
            result.append(root.val)
            for val in self.largestValues(root.right):
                result.append(val)
            return result
        elif root.right == None:
            result.append(root.val)
            for val in self.largestValues(root.left):
                result.append(val)
            return result
        result.append(root.val)
        left_list = self.largestValues(root.left)
        right_list = self.largestValues(root.right)
        min_length = min(len(left_list),len(right_list))
        for val in range(min_length):
            result.append(max(left_list[val],right_list[val]))
        for val in range(min_length, len(left_list)):
            result.append(left_list[val])
        for val in range(min_length, len(right_list)):
            result.append(right_list[val])
        return result

 

你可能感兴趣的:(python,leetcode,leetcode)