JavaScript Node Uncle: Finding a Node's Uncle in a Binary Tree
/**
-
Returns the uncle node of the current node.
-
@returns {Node} The uncle node of the current node, or undefined if there is no uncle. */ get uncle() { // Check if current node has a parent. if (!this.parent) { return undefined; }
// Check if current node has a grand-parent. if (!this.parent.parent) { return undefined; }
// Check if the grand-parent has two children. if (!this.parent.parent.left || !this.parent.parent.right) { return undefined; }
// So for now we know that the current node has a grand-parent and this // grand-parent has two children. Let's find out who the uncle is. if (this.nodeComparator.equal(this.parent, this.parent.parent.left)) { // The right child of the grand-parent is the uncle. return this.parent.parent.right; }
// The left child of the grand-parent is the uncle. return this.parent.parent.left; }
原文地址: https://www.cveoy.top/t/topic/qhpc 著作权归作者所有。请勿转载和采集!