leetcode 刷题之路 29 Validate Binary Search Tree

来源:互联网 发布:拳皇13出招优化补丁 编辑:程序博客网 时间:2024/05/01 16:58

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.
题目要求判断一个二叉树是否为二叉查找树。
如果一个二叉树进行中序遍历后得到的结果为一个升序序列,则该二叉树为二叉查找树。
测试通过代码:
/** * 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) {TreeNode *lastNode = NULL;return helper(root, lastNode);}static bool helper(TreeNode *root, TreeNode *&lastNode){if (root == NULL)return true;bool b1 = helper(root->left, lastNode);bool b2 = true;if (lastNode!=NULL)b2 = lastNode->val < root->val;lastNode = root;bool b3 = helper(root->right, lastNode);return b1&&b2&&b3;}};


0 0