【小熊刷题】Validate Binary Search Tree <含recursion>

来源:互联网 发布:c语言程序的基本单位 编辑:程序博客网 时间:2024/05/03 02:23

Question

Given a binary tree, determine if it is a valid Binary Search Tree (BST).

这里需要注意,是左侧所有的node value都小于root(parent),右侧所有的value都大于它上面的root(parent),每一个node都是一个BST。 书中举了个例子:

10

/ \

5 15 ——– binary tree (1)

/ \6 20

这样6不应该在右边,所以不是一个valid binary search tree(虽然是binary tree)

最简单的方法就是看每一个node的left child和right child是不是符合规则,就要用到recursion。

先复习一下dave老头曾经强调的recursion四原则:
 Do the base cases first

 Recur only with simpler cases

 Don’t modify and use non-local variables

 Don’t look down

My Solution

Runtime: O(n^2), stack space: O(n)

/** * 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;        return isValidBST(root.left) && isValidBST(root.right)        && isSubtreeLessThan(root.left, root.val)         && isSubtreeGreaterThan(root.right, root.val);    }    public boolean isSubtreeLessThan(TreeNode node, int val){        if(node == null) return true;        return node.val < val && isSubtreeLessThan(node.left, val) && isSubtreeLessThan(node.right, val);    }     public boolean isSubtreeGreaterThan(TreeNode node, int val){        if(node == null) return true;        return node.val > val && isSubtreeGreaterThan(node.left, val) && isSubtreeGreaterThan(node.right, val);    } }

My Initial thoughts - In-order traversal

之前想了一下,觉得如果traverse方法得当应该也可以看得出来,看了书里的hints,确实如此。如果用in-order traversal只要traverse过程中都在increase value就可以了 (strict monotonic increasing order https://en.wikipedia.org/wiki/Monotonic_function)

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    private TreeNode prev; // store the current previous value    public boolean isValidBST(TreeNode root) {        if(root == null) return true;        return ifMonotonicIncrease(root);    }    public boolean ifMonotonicIncrease(TreeNode root){ // in-order is test left and then root and then right        if(root == null) return true;        if(ifMonotonicIncrease(root.left)){            if(prev != null && root.val <= prev.val) return false;            prev = root;            return ifMonotonicIncrease(root.right);        }else{            return false;        }    }}

第三种方法

书中还说了另一种方法来优化第一种brute force的方法,就是把每个node的值得范围传下去(BFS),如果当前node的值不在范围内就is not valid Binary Search Tree.

具体代码稍后更新~~

0 0
原创粉丝点击