TypechoJoeTheme

IT技术分享

统计

[Template] Binary Search Tree (BST)

2017-10-26
/
0 评论
/
728 阅读
/
正在检测是否收录...
10/26

[tabby title="Search"]

while(low <= high){
    int mid = low+((high-low)/2);
    int value = nums[mid];
    if(value == target){
        return mid;
    }else if(value > target){
        low = mid+1;
    }else{
        high=mid-1;
    }
}

[tabby title="Build Tree"]

import java.util.Scanner;

class TreeNode {
    int value;
    TreeNode left;
    TreeNode right;

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

public class BSTTemplate {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            nums[i] = in.nextInt();
        }           
        TreeNode root = buildTree(nums);
    }

    private static TreeNode buildTree(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }

        TreeNode root = new TreeNode(nums[0]);
        for (int i = 1; i < nums.length; i++) {
            insertNode(root, nums[i]);
        }
        return root;
    }

    private static void insertNode(TreeNode root, int value) {
        if (value < root.value) {
            if (root.left == null) {
                root.left = new TreeNode(value);
            } else {
                insertNode(root.left, value);
            }
        } else {
            if (root.right == null) {
                root.right = new TreeNode(value);
            } else {
                insertNode(root.right, value);
            }
        }
    }
}

[tabbyending]

Template
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1187/(转载时请注明本文出处及文章链接)