Leetcode 98. Validate Binary Search Tree

来源:互联网 发布:免费音乐广告制作软件 编辑:程序博客网 时间:2024/05/22 02:19

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   3

Binary tree [2,1,3], return true.
Example 2:

    1   / \  2   3

Binary tree [1,2,3], return false.

s思路:
1. 树的问题,就是遍历。一是recursive, 一是iterative。
2. 先试试用iterative的方法。利用BST特点,in-order traversal of BST是递增的序列!所以去in-order traversal,后面的数是否比前面大即可!
3. 再试试recursive:recursive就是说对每个root而言,左/右子树都是bst,同时,root->val>左子树最大值,且root->val<右子树最小值。这才符合定义!自己写的过程中,发现这个不是很容易写正确,正确的方式是:对根节点初始化最大值(mx)最小值(mn)为LONG_MAX和LONG_MIN,然后从上往下recursive时,把左子树的最大值改成root->val,表示左子树的范围是[mn,root->val];把右子树的最小值改成root->val,表示右子树的范围是[root->val,mx]。在recursive时,不断缩小这个子树的值的范围,然后每次用头节点比较是否在这个范围即可!如下图。
这里写图片描述
4. 自己先写了一个recursive, 一直调试不成功,究其原因,是没有往下recursive时实时调整子树的值域,而是用&来试图把下层的最大最小值范围统计送上去。实在是逻辑不清楚呀!

//方法1:iterative.class Solution {public:    bool isValidBST(TreeNode* root) {        //        stack<TreeNode*> ss;        TreeNode* cur=root;        long pre=LONG_MIN;//bug:容易写成int pre=INT_MIN;        while(cur||!ss.empty()){//遍历左            while(cur){                ss.push(cur);                cur=cur->left;              }               cur=ss.top();//遍历中            ss.pop();            if(cur->val<=pre) return false;            pre=cur->val;            cur=cur->right;//遍历右        }        return true;    }};//方法2:recursive.错误的方法!class Solution {public:    bool isvalid(TreeNode* root, long&mx,long&mn){        //        if(!root) return true;        long mx1,mx2,mn1,mn2;        if(isvalid(root->left,mx1,mn1)&&isvalid(root->right,mx2,mn2)&&root->val>mx1&&root->val<mn2){                mx=root->right?mx2:root->val;                mn=root->left?mn1:root->val;                return true;            }        return false;    }    bool isValidBST(TreeNode* root) {        long mx=LONG_MAX,mn=LONG_MIN;        return isvalid(root,mx,mn);         }};//方法2:recursive.正确的方法!class Solution {public:    bool isvalid(TreeNode* root, long mx,long mn){        //        if(!root) return true;        return root->val>mn&&root->val<mx&&isvalid(root->left,root->val,mn)&&isvalid(root->right,mx,root->val);    }    bool isValidBST(TreeNode* root) {        return isvalid(root,LONG_MAX,LONG_MIN);         }};
0 0
原创粉丝点击