簡體   English   中英

給定一個中序線程二叉樹和一個節點,如何找到該特定節點的父節點?

[英]Given an inorder threaded binary tree and a node, how to find the parent of that particular node?

下面鏈接中的圖像是 INORDER THREADED BINARY TREE 的示例

我們得到了一個帶有中序線程的二叉樹。 意思是,如果一個節點沒有左孩子(右孩子),則左線程(右線程)從該節點鏈接到它的中序前任(中序后繼)。

你能幫我想出可以找到節點父節點的偽代碼或算法嗎? 例如(見下圖),給定的節點是 Q,父節點必須是 I。(我們應該利用給定的想法,即二進制是有序線程)

TMI:我實際上需要這個偽代碼/算法來創建另一個算法來獲得二叉樹的后序后繼。

從圖片看來:

  • head節點是一個特殊的哨兵節點,它只是作為附加實際樹(可能為空)的哨兵節點
  • 節點有兩個額外的 boolean 標志來指示它們是否有左/右孩子

那么查找給定節點的父節點的邏輯可以如下所示:

  • 在給定節點的子樹中找到最右邊的節點。
  • 按照該節點的右鏈接到祖先。 我們知道原始節點在這個祖先節點的左子樹中。
  • 檢查祖先的左孩子是否為原始節點。 如果是這樣,我們找到了父母。
  • Go給左孩子。 我們知道原節點一定在這個節點下方的右側路徑上。 找到它,並返回我們在到達那里之前必須拜訪的父母。

這是 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.

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