zoukankan      html  css  js  c++  java
  • 【leetcode】1026. Maximum Difference Between Node and Ancestor

    题目如下:

    Given the root of a binary tree, find the maximum value V for which there exists different nodes A and B where V = |A.val - B.val| and A is an ancestor of B.

    (A node A is an ancestor of B if either: any child of A is equal to B, or any child of A is an ancestor of B.)

    Example 1:

    Input: [8,3,10,1,6,null,14,null,null,4,7,13]
    Output: 7
    Explanation: 
    We have various ancestor-node differences, some of which are given below :
    |8 - 3| = 5
    |3 - 7| = 4
    |8 - 1| = 7
    |10 - 13| = 3
    Among all possible differences, the maximum value of 7 is obtained by |8 - 1| = 7.
    

    Note:

    1. The number of nodes in the tree is between 2 and 5000.
    2. Each node will have value between 0 and 100000.

    解题思路:题目要求最大的差值的绝对值。对于任意一个节点来说,其可以得到的最大差值的绝对值只有在这四种情况中:与左子树的最大值,与左子树的最小值,与右子树的最大值,与右子树的最小值。所以只要遍历树,求出每个节点的最大差值,即可得到整棵树的最大差值。当然,为了提高效率,可以缓存每个节点的左子树的最大值、左子树的最小值、右子树的最大值、右子树的最小值。

    代码如下:

    # 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):
        dic = {} #(max,min)
        res = 0
        def recursive(self,node,num):
            self.dic[num] = (-float('inf'),float('inf'))
            if node.left != None:
                if num*2 not in self.dic:
                    self.recursive(node.left, num * 2)
                self.res = max(self.res,abs(node.val - self.dic[num*2][0]),abs(node.val - self.dic[num*2][1]))
                self.dic[num] = (max(node.val,self.dic[num][0],self.dic[num*2][0]),min(node.val,self.dic[num][1],self.dic[num*2][1]))
    
            if node.right != None:
                inx = num*2 + 1
                if inx not in self.dic:
                    self.recursive(node.right, num * 2+1)
                self.res = max(self.res,abs(node.val - self.dic[inx][0]),abs(node.val - self.dic[inx][1]))
                self.dic[num] = (max(node.val,self.dic[num][0],self.dic[inx][0]),min(node.val,self.dic[num][1],self.dic[inx][1]))
    
            if node.left == None and node.right == None:
                self.dic[num] = (node.val,node.val)
    
    
        def maxAncestorDiff(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            self.dic = {}
            self.res = 0
            self.recursive(root,1)
            #print self.dic
            return self.res
            
  • 相关阅读:
    python 安装与pip安装
    使用通配符来解决数据1和11、12/13/14的问题
    数据库中一行变多行,拆分数据
    15-哈希表 HashTable
    13-自平衡二分搜索树 AVLTree
    12-并查集 UnionFind
    11-字典树 Trie
    10-线段树 Segment Tree
    09-堆 Heap(最大堆)
    08-映射 Map
  • 原文地址:https://www.cnblogs.com/seyjs/p/10765612.html
Copyright © 2011-2022 走看看