Week2
Program--Medium
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 3Binary tree
[2,1,3]
, return true.
Example 2:
1 / \ 2 3Binary tree
[1,2,3]
, return false.
题目解析:
这是一道二叉树的问题,判断给定一颗二叉树是否符合上诉条件,即左子树所有节点值小于根节点值,右子树所有节点值大于跟节点值。仔细观察我们可以发现,树节点的值的分布永远是左 < 根 < 右。那么解决这道题的思路也是比较直接的,只要我们将树进行先序遍历,到叶子结点后,回退时,将回退前的节点记下来,与回退前的前一节点进行比较,如果回退前的值大于回退前的前一节点的值,则非法,判断返回假。
代码:
/**
* 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) {
TreeNode* lastNode = NULL;
return isValidNode(root, lastNode);
}
bool isValidNode(TreeNode* node, TreeNode* &lastNode) {
if (node == NULL) {
return true;
}
if (!isValidNode(node->left, lastNode)) {
return false;
}
if (lastNode != NULL && lastNode->val >= node->val) {
return false;
}
lastNode = node;
return isValidNode(node->right, lastNode);
}
};