法一(自己思路,复杂了):
from collections import dequeclass Solution(object):def isValidBST(self, root):""":type root: TreeNode:rtype: bool"""queue = deque()if root.left!=None:queue.append(root.left)#节点的值可能是负数,所以要用列表queue.append([root.val])queue.append("0")if root.right!=None:queue.append(root.right)queue.append([root.val])queue.append("1")while len(queue)!=0:root = queue.popleft()# nodeVals = [].extend(queue.popleft())nodeVals = []nodeVals.extend(queue.popleft())paths = queue.popleft()for i in range(len(paths)):if paths[i]=="0" and root.val>=nodeVals[i]:return Falseif paths[i]=="1" and root.val<=nodeVals[i]:return FalsenodeVals.append(root.val)if root.left!=None:queue.append(root.left)queue.append(nodeVals)queue.append(paths+"0")if root.right!=None:queue.append(root.right)queue.append(nodeVals)queue.append(paths+"1")return True
法二(官方):
利用深度遍历,如图,一看就懂
代码
class Solution {public boolean isValidBST(TreeNode root) {return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);}public boolean isValidBST(TreeNode node, long lower, long upper) {if (node == null) {return true;}if (node.val <= lower || node.val >= upper) {return false;}return isValidBST(node.left, lower, node.val) && isValidBST(node.right, node.val, upper);}
}