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.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Input: root = {3,9,20,null,null,15,7}
Output: 2Approach
Java
public class MinimumDepthBinaryTree {public static void main(String[] args) {TreeNode root = new TreeNode(3);root.left = new TreeNode(9);root.right = new TreeNode(20);root.right.left = new TreeNode(15);root.right.right = new TreeNode(7);System.out.println(minDepth(root));}static int minDepth(TreeNode root) {if (root == null)return 0;if (root.left == null && root.right == null)return 1;if (root.left == null)return 1 + minDepth(root.right);if (root.right == null)return 1 + minDepth(root.left);return Math.min(minDepth(root.left), minDepth(root.right)) + 1;}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data=data;this->left=NULL;this->right=NULL;}};int minDepth(TreeNode* root){if(root==NULL)return 0;if(root->left==NULL &&root->right==NULL)return 1;if(root->left==NULL)return 1+minDepth(root->right);if(root->right==NULL)return 1+minDepth(root->left);return min(minDepth(root->left),minDepth(root->right))+1;}int main(){TreeNode *root=new TreeNode(3);root->left=new TreeNode(9);root->right=new TreeNode(20);root->right->left=new TreeNode(15);root->right->right=new TreeNode(7);cout<<minDepth(root);return 0;}

No comments:
Post a Comment