Minimum Binary Tree depth

Source: Internet
Author: User

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);    } };

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.