给定一颗二叉树,找到它的最小深度。
Posted 菜鸟技术栈
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了给定一颗二叉树,找到它的最小深度。相关的知识,希望对你有一定的参考价值。
package com.example.tree;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class SolutionMinDepth {
public static int minDepth(TreeNode root) {
if(root == null){
return 0;
}
int leftMin = minDepth(root.left);
int rightMin = minDepth(root.right);
return Math.min(leftMin,rightMin) + 1;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(3);
TreeNode t1 = new TreeNode(9);
TreeNode t2 = new TreeNode(20);
TreeNode t5 = new TreeNode(15);
TreeNode t6 = new TreeNode(7);
root.left = t1;
root.right = t2;
t2.left = t5;
t2.right = t6;
System.out.println(minDepth(root));
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
往期内容:
以上是关于给定一颗二叉树,找到它的最小深度。的主要内容,如果未能解决你的问题,请参考以下文章