The maximum and minimum depth of the binary tree structure

The maximum and minimum depth of the binary tree structure

1. Maximum depth

Idea: Use [depth-first traversal] to obtain the maximum depth of the [left child tree] of the current point, the maximum depth of the [right child tree],
take the maximum of the two maximum depths, and then add the depth occupied by the node itself, It is the maximum depth with this node as the root. When the
recursive return to the root node, it is the maximum depth of the binary tree.

The following is the C++ implementation code:

int maxDepth(TreeNode* root) {
    
    
	if (!root)
		return 0;
	return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}

Is it stunned that it is so concise? This is the charm of recursion.

2. Minimum depth

Idea: The minimum depth is the same as the maximum depth, but the difference is that if more than one of the two child nodes is empty, then the maximum depth is used, that is, the other is not empty and the other is not empty. If both are empty, take 0.

The following is the implementation code:

int minDepth(TreeNode* root) {
    
    
	if (!root)
		return 0;
	int leftHeigh = minDepth(root->left);
	int rightHeigh = minDepth(root->right);
	if (leftHeigh == 0 || rightHeigh == 0) {
    
    
		//当某个节点的左孩子节点为空时,则不能算入最小深度中,取右孩子节点的深度,反之亦然。都为空则取0
		return max(leftHeigh, rightHeigh) + 1;
		}
	else {
    
    
		return min(leftHeigh, rightHeigh) + 1;	//这步和最大深度求法一样,只不过max换成了min
	}
}

Guess you like

Origin blog.csdn.net/h799710/article/details/106104027
Recommended