Question

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Note: A leaf is a node with no children.

Difficulty:Easy

Category:Tree, Depth-first-Search, Breadth-First-Search

Analyze

Template 1: One root

There are four steps for this template:

  1. Boundary conditions.
  2. Deal with the root value.
  3. recursive call funciton
  4. compare ouput value

There is a small mistake in the picture, the last line for this question. Use: min function

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
 public:
  int minDepth(TreeNode* root) {
    if (root == nullptr) return 0;
    if (root->left == nullptr && root->right == nullptr) return 1;
    int l = minDepth(root->left);
    int r = minDepth(root->right);
    if (r == 0) return l + 1;
    if (l == 0) return r + 1;
    return min(l, r) + 1;
  }
};
By guozetang            Updated: 2020-09-19 13:02:30

results matching ""

    No results matching ""