The depth of the root node is always 0, as there are no edges between the root and itself
Depth is calculated by counting the number of edges (or connections) from the root to the target node
The depth of a node is equal to the number of its ancestors, excluding the node itself
Depth is measured from the root down to a specific node.
Height is measured from a specific node up to the furthest leaf node.
While the depth of the tree (maximum depth of any node) is equal to the height of the tree, the depth and height of individual nodes within the tree are not necessarily the same.
Balanced Tree
Height-Balanced Trees: A binary tree is considered height-balanced if for every node, the heights of its left and right subtrees differ by at most 1.
intmaxDepth(TreeNode*root){if(!root){return0;}queue<TreeNode*>q;q.push(root);intdepth=0;while(!q.empty()){intqSize=q.size();while(qSize--){TreeNode*node=q.front();q.pop();if(!node){continue;}q.push(node->left);q.push(node->right);}depth++;}// This is wrong, because it also takes null nodes into the count// It should be depth-1returndepth;}
The return value depth is wrong, because at the bottom level it also takes null nodes into the count. It should be depth-1.
However, this can be misleading. Let’s change the code so that it prevents from inserting null nodes into the queue: