【Leecode】207Validate Binary Search Tree有效二叉搜索树

/*
2.Validate Binary Search Tree
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.
*/

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
判断一个二叉搜索树是否有效,左边子树的结点小于结点值,右边子树的结点大于结点值
思路:中序遍历
我们利用二分查找的性质,二分查找树的中序遍历是按照顺序递增的。所以我们只需要中序遍历一遍这棵树,维护前驱结点,每次检查是否满足递增关系即可。我们先中序遍历左孩子,直到没有左孩子,返回和前驱结点比较,然后递归这个节点的右孩子。即完成中序遍历过程。
Attention:
1. 前驱结点需要设置为引用类型,因为我们需要这个pre的值能够影响它在函数外部的值,即在各层递归中都同时改变。

bool in_order(TreeNode* node, TreeNode* &pre) 

http://blog.csdn.net/cinderella_niu/article/details/43115689

class Solution {
public:
    bool isValidBST(TreeNode* root) {
        TreeNode* pre = NULL;
        return middle_order(root,pre);
    }
private:
    bool middle_order(TreeNode* node, TreeNode* &pre)
    {
        if(node == NULL)
            return true;
        if(!middle_order(node->left,pre)) 
            return false;
        if(pre!=NULL && pre->val >= node->val)
            return false;
        pre = node;
        return middle_order(node->right, pre);
    }
};

版本二:java代码,来自《程序员代码面试指南IT名企算法与数据结构题目最优解—左程云著》

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        boolean res = true;
        TreeNode pre = null;
        TreeNode cur1 = root;
        TreeNode cur2 = null;
        while (cur1 != null) {
            cur2 = cur1.left;
            if (cur2 != null) {
                while (cur2.right != null && cur2.right != cur1) {
                    cur2 = cur2.right;
                }
                if (cur2.right == null) {
                    cur2.right = cur1;
                    cur1 = cur1.left;
                    continue;
                } else {
                    cur2.right = null;
                }
            }
            if (pre != null && pre.val >= cur1.val) {
                res = false;
            }
            pre = cur1;
            cur1 = cur1.right;
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值