Python代码:
Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
previous = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
if not self.isValidBST(root.left):
return False
if previous!=None and previous >= root.val:
return False
previous = root.val
return self.isValidBST(root.right)
第20行:UnboundLocalError:赋值前引用的局部变量'previous'。
Java代码:
public class Solution {
private Integer previous = null;
public boolean isValidBST(TreeNode root) {
if(root == null){
return true;
}
if(!isValidBST(root.left)){
return false;
}
if(previous != null && previous>=root.val){
return false;
}
previous = root.val;
return isValidBST(root.right);
}
}
答案 0 :(得分:0)
请改为尝试:
class Solution(object):
previous = None
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
if not self.isValidBST(root.left):
return False
if self.previous!=None and self.previous >= root.val:
return False
self.previous = root.val
return self.isValidBST(root.right)
注意previous
现在在课堂内,并使用self.previous
来访问它
编辑:要将其传递到外部,您需要传递解决方案对象
solution = Solution()
#perform something to assign a previous node
test = Test()
test.getPrev(solution)
class Test(object):
def getPrev(self, solution):
print solution.previous
答案 1 :(得分:0)
您应该只使用全局关键字。 由于previous = None在类Solution之外定义,因此要在类中使用相同的变量,请添加一行。
global previous
if previous!=None and previous >= root.val:
your logic
这将完成你的工作。