簡體   English   中英

用javascript反轉二叉樹

[英]Inverting a binary tree with javascript

我正在嘗試在 javascript 中反轉二叉樹,但我不明白為什么我沒有讓它打印我的樹。 似乎我可以在底部的示例代碼中創建我的樹,但我無法使用它來保存數據。

 // A node contains the value, left and right pointers class Node { constructor(item) { this.data = item; this.left = this.right = null; } } class BinaryTree { constructor() { this.root = null; } invert() { this.root = this.invert(this.root); } invert(node) { if (node == null) return node; /* recursive calls */ let left = this.invert(node.left); let right = this.invert(node.right); /* swap the left and right pointers */ node.left = right; node.right = left; return node; } printTree() { this.printTree(this.root); } // print InOrder binary tree traversal. printTree(node) { if (node == null) return; this.printTree(node.left); console.log(node.data + " "); this.printTree(node.right); } } /* testing for example nodes */ const tree = new BinaryTree(); tree.root = new Node(2); tree.root.left = new Node(11); tree.root.right = new Node(4); tree.root.right.left = new Node(13); tree.root.right.right = new Node(5); /* log inorder traversal of the input tree */ console.log("Inorder traversal of input tree is :"); tree.printTree(); console.log(""); /* invert tree */ tree.invert(); /* log inorder traversal of the minor tree */ console.log("Inorder traversal of binary tree is : "); tree.printTree();

我在這里做錯了什么,沒有讓它打印樹,然后反轉它。

您不能在 javascript 中重載函數,無論哪個“匹配”,它都會始終調用相同的函數。

 class Demo { overload(a) { console.log('hi'); } overload() { console.log('bye'); } overload(a, b) { console.log('wow'); } } const d = new Demo(); d.overload(); d.overload(1); d.overload(1, 2);

因為你從tree.printTree(); ,它實際上是在調用:

printTree(node) {
  if (node == null)
    return;

  this.printTree(node.left);
  console.log(node.data + " ");
  this.printTree(node.right);
}

並且您使用==而不是=== ,您實際上是在調用:

printTree() {
    if (true) {
        return;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM