Same Tree ..编写一个函数来检查它们是否相同

问题描述 投票:-4回答:1

给出两个二叉树,编写一个函数检查它们是否相同。

如果两个二叉树在结构上相同并且节点具有相同的值,则认为它们是相同的。

示例1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

输出:true示例2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

输出:错误示例3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

输出:假

javascript algorithm
1个回答
-2
投票

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

    insert(value) {

        if(!this.value) {
            this.value = value;
            return;
        }

        // Inserting to the left for values less than the current value
        if(value <= this.value) {

            if(this.left) {
                return this.left.insert(value);
            } else {
                this.left = new Node(value);
                this.left.parent = this;
            }

        // Insert to the right for the values greater than the current value
        } else {
            if(this.right) {
                return this.right.insert(value);
            } else {
                this.right = new Node(value);
                this.right.parent = this;
            }
        }

    }

    find(value) {

        if(this.value === value) {
            return this;
        }

        if(value < this.value && this.left) {
            return this.left.find(value);
        }

        if(value > this.value && this.right) {
            return this.right.find(value);
        }

        return null;
    }

    findMin(value) {
        if(!this.left) {
            return this;
        } else {
            return this.left.findMin();
        }
    }

    printInOrder(value) {
        if(this.left) {
            this.left.printInOrder();
        }

        console.log(this.value);

        if(this.right) {
            this.right.printInOrder();
        }
    }

}


class BST {
    constructor() {
        this.root = new Node();
    }

    insert(value) {
        this.root.insert(value);
    }

    find(value) {
        return this.root.find(value);
    }

    findMin(value) {
        return this.root.findMin();
    }

    printInOrder(value) {
        this.root.printInOrder();
    }
}

 console.log("first bst");
 let a1 = new BST();
 a1.insert(100);
 a1.insert(50);
 a1.insert(150);
 a1.insert(80);
 a1.insert(200);
 a1.insert(70);
 a1.insert(85)
 a1.printInOrder();

 console.log("second bst");
 let b2 = new BST();
 b2.insert(100);
 b2.insert(50);
 b2.insert(150);
 b2.insert(80);
 b2.insert(200);
 b2.insert(70);
 b2.insert(85)
 b2.printInOrder();

class Sol{
  constructor() {
  }

  isTreeSame(tree1, tree2){

  }
}

let sol = new Sol();
console.log(sol.isTreeSame(a1, b2));

© www.soinside.com 2019 - 2024. All rights reserved.