class Solution { public: vector<int> V; void postTree(TreeNode* node) { if (node != NULL) { if (node->left != NULL) { postTree(node->left); } V.push_back(node->val); if (node->right != NULL) { postTree(node->right); } } } bool isValidBST(TreeNode* root) { postTree(root); for (int i = 1; i < V.size(); i++) { if (V[i] <= V[i - 1]) { return false; } } return true; } };
补充一个python的实现:
1 class Solution: 2 def __init__(self): 3 self.lists = [] 4 5 def inOrder(self,root): 6 if root != None: 7 if root.left != None: 8 self.inOrder(root.left) 9 self.lists.append(root.val) 10 if root.right != None: 11 self.inOrder(root.right) 12 13 def isValidBST(self, root: 'TreeNode') -> 'bool': 14 self.inOrder(root) 15 n = len(self.lists) 16 for i in range(n-1): 17 if self.lists[i] >= self.lists[i+1]: 18 return False 19 return True