How to Get Category Tree Collection in Magento 2?

Get Category tree collection by the specific root category id Magento 2.

Magento has the interface to get the category tree by the Magento\Catalog\Api\CategoryManagementInterface with getTree() method.

Check the definition of the method from the interface,

/**
 * @param int $rootCategoryId
 * @param int $depth
 * @throws \Magento\Framework\Exception\NoSuchEntityException If ID is not found
 * @return \Magento\Catalog\Api\Data\CategoryTreeInterface containing Tree objects
 */
public function getTree($rootCategoryId = null, $depth = null);

If you have passed $rootCategoryId value, the result will be a tree for that category id otherwise it will return all the category tree for the store.

$depth indicates how many depths for the result.

<?php
namespace Jesadiya\CategoryTree\Model;

use Exception;
use Magento\Catalog\Api\Data\CategoryTreeInterface;
use Magento\Catalog\Api\CategoryManagementInterface;

class CategoryTree
{
    /**
     * @var CategoryManagementInterface
     */
    private $categoryManagement;

    public function __construct(
        CategoryManagementInterface $categoryManagement
    ) {
        $this->categoryManagement = $categoryManagement;
    }

    /**
     * Fetch Category Tree
     *
     * @return CategoryTreeInterface
     */
    public function getCategoryTree()
    {
        $rootCategoryId = 20;
        try {
            $categoryTreeList = $this->categoryManagement->getTree($rootCategoryId);
        } catch (Exception $exception) {
            throw new Exception($exception->getMessage());
        }
    }
}

You can explore the category tree by passing Category id you want to show as tree format,

$categoryTreeData = $this->getCategoryTree();
echo "<pre>";    print_r($category->debug());

Category with the child category will be display as children_data in the output.

Output:
Magento\Catalog\Api\Data\CategoryTreeInterface