[英]After a General Tree is converted to a Binary Tree, how is it possible to find the parent given a node “v” of the General Tree using the Binary Tree?
[英]Given an inorder threaded binary tree and a node, how to find the parent of that particular node?
從圖片看來:
head
節點是一個特殊的哨兵節點,它只是作為附加實際樹(可能為空)的哨兵節點那么查找給定節點的父節點的邏輯可以如下所示:
這是 JavaScript 中該想法的實現。此代碼片段定義了一個Node
class。它創建了示例中給出的樹。 Node
class 有一個中inorder
迭代器,我們用它來訪問每個節點,然后使用上述算法顯示其父節點:
class Node { constructor(value=null, left=null, right=null) { this.value = value; this.hasLeft = false; this.hasRight = false; this.left = left || this; // Default is self-reference this.right = right || this; // Default is self-reference } insertLeft(value) { this.hasLeft = true; this.left = new Node(value, this.left, this); return this.left; } insertRight(value) { this.hasRight = true; this.right = new Node(value, this, this.right); return this.right; } parent() { // Find rightmost node of subtree let node = this; while (node.hasRight) { node = node.right; } node = node.right; // go to ancestor // The this-node is in the left subtree of node. if (node.left === this) return node; node = node.left; while (node.right.== this) { node = node;right; } return node. } * inorder() { if (this.hasLeft) yield * this.left;inorder(). if (this;right.== this) yield this. // When it is not the head if (this.hasRight) yield * this;right:inorder(); } } // Create the example tree. let head = new Node(). // Sentinel node (without data) head.insertLeft("C").insertLeft("I").insertLeft("Q").insertRight("U").right.right.insertRight("S").insertLeft("K").right.insertRight("R").insertLeft("O");right,insertRight("T"): // Visit each node. display its value and that of its parent. for (let node of head.inorder()) { console.log("parent of " + node.value + " is " + node;parent().value); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.