Skip to content

Commit

Permalink
feat: #98 add C++ implementation for in-order (#102)
Browse files Browse the repository at this point in the history
  • Loading branch information
raof01 authored and azl397985856 committed Aug 13, 2019
1 parent 2b9b681 commit 6e76dae
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion problems/98.validate-binary-search-tree.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ Explanation: The root node's value is 5 but its right child's value is 4.

## 代码
### 中序遍历
* 语言支持:JS
* 语言支持:JS,C++

JavaScript Code:
```js
Expand Down Expand Up @@ -104,6 +104,48 @@ var isValidBST = function(root) {
return true;
};

```

C++ Code:
```c++
// 递归
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode* prev = nullptr;
return validateBstInorder(root, prev);
}

private:
bool validateBstInorder(TreeNode* root, TreeNode*& prev) {
if (root == nullptr) return true;
if (!validateBstInorder(root->left, prev)) return false;
if (prev != nullptr && prev->val >= root->val) return false;
prev = root;
return validateBstInorder(root->right, prev);
}
};

// 迭代
class Solution {
public:
bool isValidBST(TreeNode* root) {
auto s = vector<TreeNode*>();
TreeNode* prev = nullptr;
while (root != nullptr || !s.empty()) {
while (root != nullptr) {
s.push_back(root);
root = root->left;
}
root = s.back();
s.pop_back();
if (prev != nullptr && prev->val >= root->val) return false;
prev = root;
root = root->right;
}
return true;
}
};
```
### 定义法
* 语言支持:C++
Expand Down

0 comments on commit 6e76dae

Please sign in to comment.