[Leetcode] Validate Binary Search Tree

来源:互联网 发布:淘宝钻石买家号出售 编辑:程序博客网 时间:2024/06/07 22:52

题目:

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.


思路:中序遍历。中序遍历BST的顺序实际上是一个递增的序列,设置一个指针记录每一个node的前一个node,比较即可判断该BST的有效性。previous的赋值发生在遍历完左子树和当前节点值之后,遍历右子树之前。同时注意做好剪枝工作。


class Solution {public:    TreeNode* previous = nullptr;   //record the previous node of the current node        bool inorder_traversal(TreeNode* root) {        if (root == nullptr) return true;        if (!inorder_traversal(root->left)) return false;   //pruning, no need to go left        if (previous != nullptr && previous->val >= root->val) return false;        previous = root;   //the current node becomes the previous node        if (!inorder_traversal(root->right)) return false;   //try the right branch        else return true;    }        bool isValidBST(TreeNode *root) {        return inorder_traversal(root);    }};


总结:设置previous指针可以解决类似很多问题。复杂度为O(2^n).

0 0
原创粉丝点击