二叉搜索树 javascript 数组 - 数据结构

问题描述 投票:0回答:1

我正在尝试用数组构建二叉树。我想获取数组,找到根并分割左右两侧,然后根据需要在每一侧执行相同的分割,直到剩下两个数字,最低的向左,最高的向右。左侧的数字将低于右侧的数字。

class Node {
    constructor(value){
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

class BinarySearchTree{
    constructor(nums){
        this.nums = nums
        this.root = null
    }

    buildtree(nums) {

        if (nums.length <= 0) { return null} 

        let root = this.root
        //console.log(root)  null
        let mid = Math.floor(nums.length / 2)
        //console.log(nums[mid])3-just mid and 4-mid nums

        root = new Node(nums[mid])
        //console.log(root)

        let lSide = nums.slice(0, mid)
        console.log(lSide, "left side, unused")

        let rSide = nums.slice(mid  + 1, nums.length)
        console.log(rSide, "right side unused")
        
        console.log(lSide.length, rSide.length)
         //while there is something in the queue of each mini array

        //total length of array to use as a counter
        let totalLength = lSide.length + rSide.length
        console.log(totalLength)

        let i = 0;


        while(totalLength >= i){
            i++ //console.log(i) I got 7 loops through

            //if left side greater 3 and not = null
            if (lSide.length >= 3 && lSide.length != null){
                //Get the middle of the left side

                let lMid = Math.ceil(lSide.length / 2)
                //console.log(lMid)
                

                let parent = new Node(lMid)
                root.left = parent //everything DIES HERE
                //buildtree(lSide)

                //I would like to return the function after the while 
                //loop until the queue is empty but I am having no luc
                //doing so
                
            }  if (lSide <= 3 && lSide != null){
               
                if(lSide[0] < lSide[1]){
                    let child = new Node(lSide[0])
                    parent.left = child
                } else if (lSide[0] > lSide[1]){
                    let child = new Node(lSide[1])
                    parent.right = child
                } else if (rSide.length >= 3 && rSide.length != null){
                    //Get the middle of the left side
                    
                    let rMid = Math.ceil(rSide.length / 2)
                    console.log(rMid)
    
                    let parent = new Node(rMid)
                    root.left = parent
                }

                  else if (rSide <= 3 && rSide != null){
                    if(rSide[0] < rSide[1]){
                        let child = new Node(rSide[0])
                        parent.left = child
                    } else if (rSide[0] > rSide[1]){
                        let child = new Node(rSide[1])
                    }
                }
            }
        }//while
        return root
        
    }//funct
} //class



const nums = [1, 2, 3, 4, 5, 6, 7]
const bst = new BinarySearchTree(nums)
//console.log(root.nums)
console.log(bst.buildtree(nums))

以下Html代码

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <script type="module" src="myscript.js"></script>
    
    <title>Test</title>
  </head>

  <body>
    
    
  </body>

</html>

我尝试了很多不同的方法来做到这一点,这是迄今为止最好的逻辑。我把代码写出来就像我在自言自语一样。

问题出在注释中,如果到达第一个节点,请将其发送 root.left ,而 while 循环对我没有任何其他作用。我知道 while 循环仍在进行,直到变量 i 达到长度,因为我控制台记录了它。谁能帮助我在这方面取得更大进展。

我的主要问题是如何让当前代码流动而不将第一个节点记录到左侧并消失。

javascript algorithm data-structures binary-search-tree
1个回答
0
投票

要从排序数组构建二叉搜索树(BST),我们可以递归地选择数组的中间元素作为根节点,然后从数组的左半部分递归构建左子树,从数组的右半部分递归构建右子树。右半边。您的逻辑处于正确的轨道上,但是您的方法存在一些问题,特别是递归结构。

解决问题的关键是:

使用数组的中间元素作为根。 递归划分左右子数组,并将它们分别指定为当前节点的左子节点和右子节点。 基本情况:如果数组有 1 或 2 个元素,请通过确保较小的值位于左侧而较大的值位于右侧来适当处理它们。

class Node {
    constructor(value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

class BinarySearchTree {
    constructor(nums) {
        this.nums = nums;
        this.root = this.buildtree(nums);
    }

    buildtree(nums) {
        // Base case: If no elements, return null
        if (nums.length === 0) return null;

        // Find the middle element of the array
        let mid = Math.floor(nums.length / 2);
        let node = new Node(nums[mid]);

        // Recursively build the left and right subtrees
        node.left = this.buildtree(nums.slice(0, mid)); // Left subarray
        node.right = this.buildtree(nums.slice(mid + 1)); // Right subarray

        return node; // Return the current node (root of the subtree)
    }
}

// Test the implementation
const nums = [1, 2, 3, 4, 5, 6, 7];
const bst = new BinarySearchTree(nums);

// Function to print the tree structure (for testing)
function printTree(node, level = 0) {
    if (node !== null) {
        printTree(node.right, level + 1);
        console.log(" ".repeat(4 * level) + "-> " + node.value);
        printTree(node.left, level + 1);
    }
}

printTree(bst.root);
© www.soinside.com 2019 - 2024. All rights reserved.