问题遇到的现象和发生背景
刚刚开始用力扣,对力扣的执行机制不是很了解。调试语句输出和答案输出在两边都不一样。题目如下
问题相关代码,请勿粘贴截图
力扣代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
min_abs = float('inf')
pre = None
class Solution:
def getMinimumDifference(self, root: TreeNode) -> int:
traversal(root)
return min_abs
def traversal(root):
global pre,min_abs
if root is None:
return
# 中序遍历,求最小间隔
traversal(root.left) # 左
if pre is not None: # 中
min_abs = min(abs(root.val-pre.val),min_abs)
if pre is None: print("root is {}, pre is None".format(root.val)) # 调试语句
else: print("root is {}, pre is {}".format(root.val, pre.val))
pre = root
traversal(root.right) # 右
本地调试代码:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
min_abs = float('inf')
pre = None
def getMinimumDifference(root: TreeNode) -> int:
traversal(root)
return min_abs
def traversal(root):
global pre,min_abs
if root is None:
return
traversal(root.left)
if pre is not None:
min_abs = min(abs(root.val-pre.val),min_abs)
if pre is None: print("root is {}, pre is None".format(root.val))
else: print("root is {}, pre is {}".format(root.val, pre.val))
pre = root
traversal(root.right)
root = TreeNode(1)
right = TreeNode(5)
right.left = TreeNode(3)
root.right = right
ans = getMinimumDifference(root)
print(ans)
运行结果及报错内容
力扣输出:
本地输出: