98. Validate Binary Search Tree (Tree; DFS)
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.
Example 1:
2
/ \
1 3
Binary tree [2,1,3], return true.
Example 2:
1
/ \
2 3
Binary tree [1,2,3], return false.
思路:由于Binary Tree的中序遍历结果是正序,所以可以检查中序遍历的结果是否递增
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isValidBST(TreeNode* root) { if(root==NULL) return true; TreeNode* pre = NULL; //we don't need to save all nodes, only a previous node is enough to know whether it's an increase sequence return inOrderTraverse(root,pre); } bool inOrderTraverse(TreeNode* root, TreeNode* &pre){ //important to use &, otherwise new object will use a new address and the result won't bring back to caller //visit left child if(root->left) if(!inOrderTraverse(root->left,pre)) return false; //visit root if(pre==NULL) pre = new TreeNode(root->val); else if(root->val > pre->val) pre->val = root->val; else return false; //visit right child if(root->right) return inOrderTraverse(root->right, pre); else return true; } };