Packages and repositories
A package is one file holding a program ready to install: its files, plus a label with its name, its version and what else it needs. Debian and Ubuntu packages end in .deb, like tree_2.1.0-1_amd64.deb.
Packages live in a repository: a server that holds thousands of them, plus an index that lists every one. Files under /etc/apt tell your computer which repositories to trust and use.
Two programs share the work. apt, the friendly one, finds packages, works out what they need and downloads them. dpkg, the lower-level one, unpacks a .deb onto the disk and keeps the list of what is installed.
Installing tree
First, sudo apt update. sudo runs a command as root, the superuser, because installing changes system files. apt downloads each repository's latest index into /var/lib/apt/lists. Nothing is installed yet.
Now sudo apt install tree. apt looks tree up in its lists: version 2.1.0-1, with one need, written Depends: libc6 (>= 2.34). libc6 is the C library that almost every program uses.
apt checks the installed list. libc6 2.36 is already there, and 2.36 is at least 2.34, so the need is met. Only tree itself must be fetched. A missing need would be fetched too.
apt downloads tree_2.1.0-1_amd64.deb from the repository into /var/cache/apt/archives. It checks the file against the checksum in the signed index, so a damaged or altered download is refused.
apt hands the .deb to dpkg. Inside are three parts: a format number, the control part (the label) and the data part (the files). dpkg copies the 7 files into place: the program to /usr/bin/tree.
dpkg sets the package up and writes it into its database, /var/lib/dpkg/status: tree, version 2.1.0-1, installed. That record is how apt later knows what you have.
Using and removing
Done. which tree shows where the new command lives: /usr/bin/tree. Type tree and it draws the folders below where you are. 7 files arrived and one record was written.
sudo apt remove tree deletes the files but keeps settings files; purge deletes those too. Careful: apt also removes packages that need the one you remove. Read the list it prints before you answer Y.
What happens
;; step 1/11 · package package tree_2.1.0-1_amd64.deb name tree version 2.1.0-1 arch amd64 (the kind of CPU it is built for) needs libc6 (>= 2.34) files 7, among them /usr/bin/tree
The example is Debian 12 ("bookworm"), where tree is version 2.1.0-1 and needs libc6 (>= 2.34). Ubuntu works the same way with its own versions. The terminal shows only the key lines apt and dpkg print. sudo asks for your own password and only works if your account is allowed to use it. On a fresh Debian install that may need setting up first.