`

Verify if a tree is a binary search tree(BST)

 
阅读更多

原创转载请注明出处:http://agilestyle.iteye.com/blog/2360893

 

Binary Search Tree

  • any node in left sub-tree < its parent
  • any node in rigth sub-tree > its parent

核心思想:递归

recursively to check values within range

  • recursion, update range for both left and right sub-trees and continue verifying
  • initial range for the root node (Integer.minimal, Integer.maximum)
package org.fool.java.test;

public class VerifyBSTTest {
    public static void main(String[] args) {
        //       4
        //    2     6
        //  1   3  5  7
        Tree myTree = new Tree(4);
        myTree.left = new Tree(2);
        myTree.right = new Tree(6);
        myTree.left.left = new Tree(1);
        myTree.left.right = new Tree(3);
        myTree.right.left = new Tree(5);
        myTree.right.right = new Tree(7);

        System.out.println("My tree is BST? " + ifBST(myTree, Integer.MIN_VALUE, Integer.MAX_VALUE));
    }

    // the key of this algorithm is to keep track of the reasonable range for current focus node and its sub-trees
    // so we need small and large as two range index values
    private static boolean ifBST(Tree a, int small, int large) {
        // firstly check if Tree is a valid tree node or null
        if (a == null) {
            return true;    // if no elements, return true
        }

        // now check if the current tree node is within (small, large)
        if (a.value > small && a.value < large) {
            // call the recursive part to check its' left and right sub-trees
//            boolean leftBST = ifBST(a.left, small, a.value);
//
//            boolean rightBST = false;
//
//            if(leftBST) {   // if leftBST == false, do not need to check the right half
//                rightBST = ifBST(a.right, a.value, large);
//            }
//
//            return rightBST;

            return ifBST(a.left, small, a.value) && ifBST(a.right, a.value, large);
        } else {
            return false;   // which means the current node finds inappropriate node, return false immediately
        }
    }
}

class Tree {
    public int value;
    public Tree left;
    public Tree right;

    public Tree(int value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

Console Output


 

Reference

https://www.youtube.com/watch?v=aNtDir94pcA&list=PLlhDxqlV_-vkak9feCSrnjlrnzzzcopSG&index=44 

https://en.wikipedia.org/wiki/Binary_search_tree 

  • 大小: 9.6 KB
分享到:
评论

相关推荐

    verify-complete-binary-tree.rar_verify

    在IT领域,排序二叉树是一种特殊的二叉树数据结构,它的每个节点的值都大于其左子树中任意节点的值...通过分析“verify-complete-binary-tree.cpp”的源代码,我们可以深入理解这些概念,并学习如何在实践中应用它们。

    selectTree.rar

    &lt;select id="demo" lay-filter="demo" lay-search lay-verify="required" layui-select-tree&gt; ``` 接下来,我们需要编写JavaScript代码来初始化并填充下拉树。layui的API提供了`form.on('select(name)', callback)`...

    a project model for the FreeBSD Project.7z

    A project model is a means to reduce the communications overhead in a project. As shown by [Brooks, 1995], increasing the number of project participants increases the communication in the project ...

    Designing Control Loops for Linear and Switching Power Supplies

    It helps engineers measure their system, showing how to verify if a prototype is stable and features enough design margin. Moreover, professionals learn how to secure high-volume production by bench-...

    MD5Verify MD5VERIFY

    MD5Verify是一款用于验证文件完整性的工具,主要利用MD5哈希算法来检查文件是否在传输或存储过程中被篡改。MD5哈希算法是一种广泛使用的加密散列函数,能够生成一个128位(16字节)的散列值,通常表示为32个十六进制...

    vue-drag-verify_verify_dragVerify卡顿_thousandm5p_vue_silly9fx_

    1. **Vue组件优化**:Vue提供了多种优化手段,如懒加载、异步组件、动态组件、v-if与v-show的使用、以及组件的缓存等。在处理大量数据或复杂交互时,这些优化策略可以提升组件性能,避免卡顿现象。 2. **虚拟DOM**...

    CheckNewPointMakesSimplex_newsimplex_verify_源码

    Verify that a new point that is to be added to an existing simplex will% form a new simplex. If not then delete some points from the existing simplex% or adjust the new point very slightly so ...

    vs版本管理工具最新版AnkhSvn-2.6.12735

    Verify if the solution is connected to AnkhSVN Right click the solution file. If you have an option that says 'Add to Subversion', your Solution is not connected yet Click Add to Subversion and ...

    How To Verify the Word Size (32bit vs 64bit) of the Oracle Binary on MS Windows systems

    "确定 Oracle 二进制文件的字长(32 位 vs 64 位)在 MS Windows 系统中的方法" 在 MS Windows 系统中,确定 Oracle 二进制文件的字长(32 位 vs 64 位)非常重要。这篇文章将介绍多种方法来确定 Oracle 数据库软件...

    LeetCode最全代码

    * [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search]...

    Universal-USB-Installer

    is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may ...

    UIA Verify

    "屏幕取词"是词典软件(如:金山词霸)里面一个必要功能。...微软有一个开源工具 UIA Verify 是基于UI Automation API的,该程序也有一个取词功能(菜单 Mode -&gt; Hover Mode),可以参考看看它的实现方法。

    WizFlow网页编辑

    such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library...

    hibernate-shards.jar

    such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library...

    verify code_verify_verifyappcode_android_

    "verify code_verify_verifyappcode_android_" 这个标题所指的,很可能是关于实现一个自定义验证码输入框(VercodeEditText)的源码项目。在Android应用中,这种控件通常具有特殊的格式要求,如限制输入字符数量、...

    Verify-Your-Vote: A Verifiable Blockchain-based Online Voting Protocol

    基于形式化验证工具ProVerif的区块链投票协议形式化验证,方便初学者复现从而理解形式化验证在智能合约领域的应用

    hello_world.vhdl.zip_verify

    A "Hello world" program is a computer program that outputs "Hello, world" on a display device. Because it is typically one ... It is also used to verify that a language or system is operating correctly.

    tfgg-verify_1.0.1.zip

    if(res){ this.$refs.verifyElement.reset();//验证成功后一定要调用重置方法,否则第二次点击江湖判定为通过 console.log('验证成功') } console.log(res); }, /* 显示校验弹窗 */ verifyFasong(){ ...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor ...

Global site tag (gtag.js) - Google Analytics