Ideas: Recursive method.
Input: Root Node of a binary tree;
Output: Minimum depth of a binary tree.
Minimum depth Definition: Number of nodes in the shortest path from the root node to the leaf node.
The algorithm is as follows::
Binary Trees are divided into the following situations:
- The input root node is empty and return null;
- The input root node is not empty, the left subtree is empty, and the right subtree is empty. The minimum depth 1 is returned;
- The input root node is not empty, the left subtree is empty, and the right subtree is not empty. The minimum depth + 1 of the right subtree is returned;
- The input root node is not empty, the left subtree is not empty, and the right subtree is empty. The minimum depth + 1 of the Left subtree is returned;
- If the input root node is not empty and left and right subtree is not empty, a smaller value + 1 is returned for the left and right subtree.
The Code is as follows::
/** * Definition for binary tree * 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 == NULL ) return NULL; if(root->left==NULL && root->right == NULL) return 1; else if(root->left == NULL && root->right !=NULL) return minDepth(root->right)+1; else if(root->left !=NULL && root->right ==NULL) return minDepth(root->left)+1; else if(root->left !=NULL && root->right != NULL) return minDepth(root->left)<=minDepth(root->right)?(minDepth(root->left)+1):(minDepth(root->right)+1); } };