📅  最后修改于: 2023-12-03 15:40:22.762000             🧑  作者: Mango
有一颗二叉树,每个节点都有一个非负整数值。现在给定一个整数X,我们需要从这棵树中找出一个节点, 使得该节点的值与X异或后二进制表示中的1的个数最小,返回该节点值。
我们需要用位运算来比较每个节点与X的二进制异或值的1位数量,选择1位数量最小的节点。
具体方法如下:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.result = float('inf')
self.target = 0
def findSmallNode(self, root: TreeNode, target: int) -> int:
if root is None:
return -1
self.target = target
self.dfs(root, 0)
return self.result
def dfs(self, node: TreeNode, count: int):
if node is None:
return
xored = node.val ^ self.target
one_count = bin(xored).count('1')
if node.left is None and node.right is None:
if one_count < self.result:
self.result = one_count
return
self.dfs(node.left, count + one_count)
self.dfs(node.right, count + one_count)
return
我们可以通过以下样例来测试我们的代码:
root = TreeNode(3)
root.left = TreeNode(5)
root.right = TreeNode(2)
root.left.left = TreeNode(1)
root.left.right = TreeNode(4)
root.right.left = TreeNode(4)
root.right.right = TreeNode(3)
solution = Solution()
assert solution.findSmallNode(root, 6) == 1