Recover Binary Search Tree
Q:
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
A:
中序遍历,比较前后元素大小
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isValidBST(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function TreeNode* cur = root; stack<TreeNode*> s; int pre = -0x7fffffff; while (cur || !s.empty()) { while (cur) { s.push(cur); cur = cur->left; } if (!s.empty()) { cur = s.top(); if (cur->val <= pre) return false; pre = cur->val; cur = cur->right; s.pop(); } } return true; } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号