Return all ancestors of $node. Just look by getParent().
The first returned node is the direct parent. The last the topmost.

@param CanHaveParent $node

@return Node[]
488230
protected function collectAncestors(CanHaveParent $node)
    {
        $child = $node;
        $i = 0;

        $parents = [];

        while($parent = $child->getParent()) {

            if ($i >= $this->_maxDepth) {
                throw new OverflowException("Giving up to collect parents after $i iterations.");
            }

            $parents[] = $parent;
            $child = $parent;
            $i++;
        }

        return $parents;
    }
1280066
public function processNode(Node $node, Scope $scope): array
    {
        $returnType = $node->getReturnType();

        if (!$returnType instanceof Node\NullableType) {
            return [];
        }

        /** @var Reflection\ClassReflection $classReflection */
        $classReflection = $scope->getClassReflection();

        if ($classReflection->isAnonymous()) {
            return [
                \sprintf(
                    'Method %s() in anonymous class has a nullable return type declaration.',
                    $node->name->name
                ),
            ];
        }

        return [
            \sprintf(
                'Method %s::%s() has a nullable return type declaration.',
                $classReflection->getName(),
                $node->name->name
            ),
        ];
    }
1041338
protected function getParentsHierarchyField() {
		// see if we've got Parent values
        $parents = array();

        $parent = $this->owner;
        while ($parent && $parent->ParentID) {
            $parents[] = (int) $parent->ParentID;
            $parent = $parent->Parent();
            // fix for odd behaviour - in some instance a node is being assigned as its own parent. 
            if ($parent->ParentID == $parent->ID) {
                $parent = null;
            }
        }
        return $parents;
	}
31704
public function getRootFamilies()
    {
        $root = [];
        foreach ($this->getFamilies() as $family) {
            if ($family->isInstantiable()) {
                $p = $family->getParent();
                if (!$p || ($p && !$p->isInstantiable())) {
                    $root[$family->getCode()] = $family;
                }
            }
        }

        return $root;
    }
200647
public function dumpNode(BaseNode $node)
    {
        return '<?php'.PHP_EOL.PHP_EOL.'return ['.parent::dumpNode($node).PHP_EOL.'];'.PHP_EOL;
    }
547346
protected function getPrivateNodes() {
		if (!Member::currentUserID()) {
			return array();
		}
		$groups = Member::currentUser()->Groups()->column();

		if (!count($groups)) {
			return $groups;
		}

		$fields = $this->queryFields();
		$query = new SQLQuery($fields, '"'.$this->baseClass.'"');
		$query = $query->setOrderBy($this->itemSort);
		$query->addWhere('"CanViewType" IN (\'OnlyTheseUsers\')');
		if (Permission::check('ADMIN')) {
			// don't need to restrict the canView by anything
		} else {
			$query->addInnerJoin('SiteTree_ViewerGroups', '"SiteTree_ViewerGroups"."SiteTreeID" = "SiteTree"."ID"');
			$query->addWhere('"SiteTree_ViewerGroups"."GroupID" IN (' . implode(',', $groups) . ')');
		}

		$this->adjustPrivateNodeQuery($query);
		$this->adjustForVersioned($query);
		$sql = $query->sql();

		$results = $query->execute();
		return $results;
	}
1339425
protected function traverseNode(Node $node) : Node
    {
        foreach ($node->getSubNodeNames() as $name) {
            $subNode =& $node->$name;

            if (\is_array($subNode)) {
                $subNode = $this->traverseArray($subNode);
                if ($this->stopTraversal) {
                    break;
                }
            } elseif ($subNode instanceof Node) {
                $traverseChildren = true;
                foreach ($this->visitors as $visitor) {
                    $return = $visitor->enterNode($subNode, $traverseChildren);
                    if (null !== $return) {
                        if ($return instanceof Node) {
                            $subNode = $return;
                        } elseif (self::DONT_TRAVERSE_CHILDREN === $return) {
                            $traverseChildren = false;
                        } elseif (self::STOP_TRAVERSAL === $return) {
                            $this->stopTraversal = true;
                            break 2;
                        } else {
                            throw new \LogicException(
                                'enterNode() returned invalid value of type ' . gettype($return)
                            );
                        }
                    }
                }

                if ($traverseChildren) {
                    $subNode = $this->traverseNode($subNode);
                    if ($this->stopTraversal) {
                        break;
                    }
                }

                foreach ($this->visitors as $visitor) {
                    $return = $visitor->leaveNode($subNode);
                    if (null !== $return) {
                        if ($return instanceof Node) {
                            $subNode = $return;
                        } elseif (self::STOP_TRAVERSAL === $return) {
                            $this->stopTraversal = true;
                            break 2;
                        } elseif (\is_array($return)) {
                            throw new \LogicException(
                                'leaveNode() may only return an array ' .
                                'if the parent structure is an array'
                            );
                        } else {
                            throw new \LogicException(
                                'leaveNode() returned invalid value of type ' . gettype($return)
                            );
                        }
                    }
                }
            }
        }

        return $node;
    }
401958
def _ancestors(self):
        
        # return list of ancestor nodes starting with self.parent and ending with root
        _ancestors=[]
        _n = self
        while _n.parent:
            _n = _n.parent
            _ancestors.append(_n)
        return _ancestors
528429
public function getAncestors()
    {
        if($this->isRoot())
        {
            return array();
        }

        if($this->ancestors === null)
        {
            $qb = $this->getManager()->getConfiguration()->getBaseQueryBuilder();
            $alias = $this->getManager()->getConfiguration()->getQueryBuilderAlias();

            $qb->andWhere("$alias.".$this->getLeftFieldName()." < :lft1")
                ->setParameter('lft1', $this->getLeftValue())
                ->andWhere("$alias.".$this->getRightFieldName()." > :rgt1")
                ->setParameter('rgt1', $this->getRightValue())
                ->orderBy("$alias.".$this->getLeftFieldName(), "ASC");
            if($this->hasManyRoots())
            {
                $qb->andWhere("$alias.".$this->getRootFieldName()." = :root")
                    ->setParameter('root', $this->getRootValue());
            }

			$q = $qb->getQuery();
			if ($this->getManager()->getConfiguration()->isQueryHintSet()){
				$q = $this->getManager()->addHintToQuery($q);
			}
			$results = $q->getResult();

            $this->ancestors = array();
            foreach($results as $result)
            {
                $this->ancestors[] = $this->getManager()->wrapNode($result);
            }
        }

        return $this->ancestors;
    }
99430
public function getAllParents(Node $node = null, $lang = null)
    {
        if (is_null($node)) {
            return array();
        }

        $qb = $this->createQueryBuilder('node');

        // Directly hydrate the nodeTranslation and nodeVersion
        $qb->select('node', 't', 'v')
            ->innerJoin('node.nodeTranslations', 't')
            ->leftJoin(
                't.publicNodeVersion',
                'v',
                'WITH',
                't.publicNodeVersion = v.id'
            )
            ->where('node.deleted = 0');

        if ($lang) {
            $qb->andWhere('t.lang = :lang')
                ->setParameter('lang', $lang);
        }

        $qb->andWhere(
            $qb->expr()->andX(
                $qb->expr()->lte('node.lft', $node->getLeft()),
                $qb->expr()->gte('node.rgt', $node->getRight())
            )
        );

        $qb->addOrderBy('node.lft', 'ASC');

        return $qb->getQuery()->getResult();
    }
957228
public function getInternalLinks( \DOMNode $node ) : array
	{
		$this->guardHasOwnerDocument( $node );

		$internalLinks = [];
		$xpath         = new \DOMXPath( $node->ownerDocument );
		$aTags         = $xpath->query( '*//a[@href]' );

		/** @var \DOMElement $aTag */
		foreach ( $aTags as $aTag )
		{
			$href = $aTag->getAttribute( 'href' );
			if ( !$this->isHyperRefIgnored( $href ) )
			{
				$internalLinks[] = $aTag;
			}
		}

		return $internalLinks;
	}
1169887
public function getFirstChild(AbstractNestedNode $node)
    {
        $children = $this->getDescendants($node, 1);
        if (0 < count($children)) {
            return $children[0];
        }

        return;
    }
1286336
def get_ancestors(self):
        
        ancestors = []
        if self._meta.proxy_for_model:
            # the current node is a proxy model; our result set
            # should use the same proxy model, so we need to
            # explicitly fetch instances of that model
            # when following the 'parent' relation
            cls = self.__class__
            node = self
            while node.parent_id:
                node = cls.objects.get(pk=node.parent_id)
                ancestors.insert(0, node)
        else:
            node = self.parent
            while node:
                ancestors.insert(0, node)
                node = node.parent
        return ancestors
924065
public function getSiblings(Node $node, $includeHiddenFromNav = true)
    {
        $this->init();
        $siblings = array();

        if (false !== $parent = $this->getParent($node)) {
            $siblings = $this->getChildren($parent, $includeHiddenFromNav);

            foreach ($siblings as $index => $child) {
                if ($child === $node) {
                    unset($siblings[$index]);
                }
            }
        }

        return $siblings;
    }
216712
def get_ancestors(self, include_self=False, depth=None):
        """"""
        if self.is_root_node():
            if not include_self:
                return self._toplevel().objects.none()
            else:
                # Filter on pk for efficiency.
                return self._toplevel().objects.filter(pk=self.pk)

        params = {"%s__child" % self._closure_parentref():self.pk}
        if depth is not None:
            params["%s__depth__lte" % self._closure_parentref()] = depth
        ancestors = self._toplevel().objects.filter(**params)
        if not include_self:
            ancestors = ancestors.exclude(pk=self.pk)
        return ancestors.order_by("%s__depth" % self._closure_parentref())
1161771
private function updateBestNodeCandidates(Element $node, array $nodeCandidates): array {
        if (!in_array($node->parent(), $nodeCandidates, true)) {
            if ($node->parent() instanceof Element) {
                $nodeCandidates[] = $node->parent();
            }
        }

        if ($node->parent() instanceof Element) {
            if (!in_array($node->parent()->parent(), $nodeCandidates, true)) {
                if ($node->parent()->parent() instanceof Element) {
                    $nodeCandidates[] = $node->parent()->parent();
                }
            }
        }

        return $nodeCandidates;
    }
331119
public function getParents()
    {
        $parent = $this->with($this->_with)->getParent();
        $data = [];
        while ($parent) {
            $data[] = $parent;
            $parent = $parent->with($this->_with)->getParent();
        }

        return array_reverse($data);
    }