Validate Binary Search Tree

来源:互联网 发布:淘客助手插件mac版 编辑:程序博客网 时间:2024/06/06 07:17

题目名称
Validate Binary Search Tree—LeetCode链接

描述
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.

分析
  一个很简单的思路就是利用二叉树的中序遍历,如果二叉树的中序遍历的节点的值是递增的,则为二叉搜索树。

C++代码

/** * 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) {        vector<TreeNode*> node;        inorder(root,node);        int size = node.size();        if(size>1) {            for(int i=1;i<size;i++) {                if(node[i]->val<=node[i-1]->val)                    return false;            }        }        return true;    }private:    void inorder(TreeNode* root,vector<TreeNode*> &vec){       if(root) {           inorder(root->left,vec);           vec.push_back(root);           inorder(root->right,vec);       }     }};

总结
  二叉树的很多问题都可以利用二叉树的遍历来解决,所以二叉树的遍历代码一定要熟记。

0 0
原创粉丝点击