LeetCode 题解(53): Validate Binary Search Tree

来源:互联网 发布:linux解压rpm文件 编辑:程序博客网 时间:2024/06/06 03: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.
题解:

自己把自己搅晕了,居然还莫名其妙弄对了。

思路是按In-order遍历树,则当前元素必须比下一个访问的元素小,或者理解为下一个元素必须比当前元素大。用Current记录当前元素的值。沿左子树前进,若当前节点没有左子树,比较当前节点值和Current值(记录的其实是上一个访问的节点的值),若大于,更新Current的值为当前节点值,否则直接返回False。

C++版:

class Solution {public:    bool isValidBST(TreeNode *root) {        if(!root)            return true;                int current = numeric_limits<int>::min();        bool value = preTrav(root, current);        return value;    }        bool preTrav(TreeNode* node, int & current) {                bool temp = true;        if(node->left) {            temp = preTrav(node->left, current);            if(!temp)                return false;        }                 if(node->val <= current)            return false;        current = node->val;        if(node->right) {            temp = preTrav(node->right, current);            if(!temp)                return false;        }        return temp;    }    };

简便的做法是将In-order遍历的值记录下来,然后再看前一个元素是否小于后一个元素。但是需要额外O(n)空间。

Java版:

public class Solution {    public boolean isValidBST(TreeNode root) {        if(root == null)            return true;                ArrayList<Integer> nodes = new ArrayList<Integer>();        inTrav(root, nodes);                for(int i = 1; i < nodes.size(); i++) {            if(nodes.get(i) <= nodes.get(i-1))                return false;        }                return true;    }        void inTrav(TreeNode root, ArrayList<Integer> nodes) {        if(root.left != null) {            inTrav(root.left, nodes);        }                nodes.add(root.val);                if(root.right != null)             inTrav(root.right, nodes);    }}

Python版:

class Solution:    # @param root, a tree node    # @return a boolean    def isValidBST(self, root):        if root == None:            return True        value = []        self.inOrder(root, value)        for i in range(1, len(value)):            if value[i] <= value[i-1]:                return False        return True                def inOrder(self, root, value):        if root.left != None:            self.inOrder(root.left, value)                    value.append(root.val)                if root.right != None:            self.inOrder(root.right, value)


0 0