zoukankan      html  css  js  c++  java
  • js实现输入某串数字,构建完全二叉树,并判断是否为二叉搜索树

    思路:若为二叉搜索树,则中序遍历为递增的

    let arr = [15,8,16,6,10];
    let pindex = [];
    function Node(){
    this.root = null;
    this.left = null;
    this.right = null;
    }

    //构建完全二叉树
    function CCtree(node,i){
    let leftIndex = 2*i+1;
    let rightIndex = 2*i+2;

    if(leftIndex < arr.length){
    let newNode = new Node();
    newNode.root = arr[leftIndex];
    node.left = newNode;
    CCtree(newNode,leftIndex);
    }
    if(rightIndex < arr.length){
    let newNode = new Node();
    newNode.root = arr[rightIndex];
    node.right = newNode;
    CCtree(newNode, rightIndex);
    }
    }

    //中序遍历

    function VinIndex(node){
    if(node.left){
    if(node.left.left){
    VinIndex(node.left);
    }
    else{
    pindex.push(node.left.root);
    }
    }
    pindex.push(node.root);
    if(node.right){
    if(node.right.left){
    VinIndex(node.right)
    }
    else{
    pindex.push(node.right.root);
    }
    }
    }
    var node = new Node();
    node.root = arr[0];
    CCtree(node, 0); //索引i是从0开始构建
    VinIndex(node);
    for(let i=0;i<pindex.length-1;i++){
    for(let j=i+1;j<pindex.length;j++){
    if(pindex[i]>pindex[j]){
    i=pindex.length-1;
    j=pindex.length;
    console.log("False")
    }
    if(i===pindex.length-2 && j===pindex.length-1){
    console.log("True")
    }
    }
    }

  • 相关阅读:
    洛谷1509 找啊找啊找GF
    要怎样努力,才能成为很厉害的人?
    随笔
    2018NOIP模拟题 曲线
    洛谷4147 玉蟾宫
    洛谷2258 子矩阵
    Vijos 纸牌
    [leetcode] Word Break
    [leetcode] Maximum Binary Tree
    [leetcode] Binary Tree Preorder Traversal
  • 原文地址:https://www.cnblogs.com/lzcblog/p/10636122.html
Copyright © 2011-2022 走看看