The maximum value of the exclusive-OR array leetcode-421- * two numbers (prefix tree)

Subject description:

 

 

method one:

class Solution:
     DEF findMaximumXOR (Self, the nums: List [int]) -> int: 
        the root = the TreeNode (-1 ) 
        
        for NUM in the nums: 
            cur_node = the root # current Node 
            
            for I in Range (0, 32):                # representatives 32-bit 
                # Print NUM, <<. 1 (31 is - I), & NUM (<<. 1 (31 is - I)) 
                IF NUM & (<<. 1 (31 is - I)) == 0:     # If the current position and result of the operation is 1, then left to go 
                    IF  not cur_node.left: 
                        cur_node.left = TreeNode (0) 
                    cur_node= Cur_node.left
                 the else :                             # If the current position and results of operations is 0, then turn right to go 
                    IF  not cur_node.right: 
                        cur_node.right = TreeNode (1 ) 
                    cur_node = cur_node.right 
            cur_node.left = TreeNode (NUM)         # in the last leaf nodes left the record about the value of this number 
                    
        RES = 0
         for NUM in nums: 
            cur_node = root 
            
            for i in the Range (0, 32 ):
                 #cur_node.val Print, cur_node.left, cur_node.right 
                IF & (<<. 1 (31 is - I)) == 0 NUM:      # calculation result is 0, can go to the right if it right away, because the right sub 1 represents the tree, so different on this one or will get 1 
                    IF cur_node.right:            # can walk right 
                        cur_node = cur_node.right # to go right 
                    the else :                         # can not go to the right 
                        cur_node = cur_node.left # Jiuwang left to go 
                the else :                             # calculation result is 1, if they can go left, you go to the left, because the left subtree represents 0, which will be exclusive or 1 
                    IF cur_node.left:             # can go left 
                        cur_node = cur_node.left # to go left
                    the else :                         # can not go left 
                        cur_node = cur_node.right # to go right   
            TEMP = cur_node.left.val              # obtained value of the number stored in this path 
                
            res = max (res, NUM ^ TEMP)            # each refresh is res maximum 
                
        return RES

 

Guess you like

Origin www.cnblogs.com/oldby/p/11619176.html