lintcode-验证查找二叉树-95

来源:互联网 发布:sam软件和au 编辑:程序博客网 时间:2024/06/05 02:09

给定一个二叉树,判断它是否是合法的二叉查找树(BST)

一棵BST定义为:

  • 节点的左子树中的值要严格小于该节点的值。
  • 节点的右子树中的值要严格大于该节点的值。
  • 左右子树也必须是二叉查找树
样例

一个例子:

   1  / \ 2   3    /   4    \     5

上述这棵二叉树序列化为"{1,2,3,#,#,4,#,#,5}".

解题思路:如果是查找二叉树,中序遍历必然有序。

/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {public:       void LDR(vector<int> &vec,TreeNode *root){        if(!root)            return ;        LDR(vec,root->left);        vec.push_back(root->val);        LDR(vec,root->right);    }    bool isValidBST(TreeNode *root) {        if(!root)            return true;        vector<int> vec;        LDR(vec,root);                int last=vec[0];        vec.erase(vec.begin());        for(auto e:vec){            if(last>=e)                return false;            last=e;            }        return true;    }};


0 0
原创粉丝点击