求二叉树的最小深度java_LeetCode简单题:111. 二叉树的最小深度(Python,C++,Java)...

一.解法

https://leetcode-cn.com/problems/minimum-depth-of-binary-tree/

要点:递归,树

Python,C++,Java都用了相同的递归方法,类似104的最大深度,有个坑是[1,2]得到的结果是2,因为只有2这个节点,不能把空节点算作一个叶子节点,所以加了root.left==None和root.right==None的单独情况

二.Python实现

# Definition for a binary tree node.

# class TreeNode:

# def __init__(self, x):

# self.val = x

# self.left = None

# self.right = None

class Solution:

def minDepth(self, root: TreeNode) -> int:

if root==None:

return 0

if root.left==None:

return 1+self.minDepth(root.right)

if root.right==None:

return 1+self.minDepth(root.left)

return min(self.minDepth(root.left),self.minDepth(root.right))+1

三.C++实现

/**

* 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) return 0;

if(!root->right) return 1+minDepth(root->left);

if(!root->left) return 1+minDepth(root->right);

return min(minDepth(root->left),minDepth(root->right))+1;

}

};

四.java实现

/**

* Definition for a binary tree node.

* public class TreeNode {

* int val;

* TreeNode left;

* TreeNode right;

* TreeNode(int x) { val = x; }

* }

*/

class Solution {

public int minDepth(TreeNode root) {

if(root==null) return 0;

if(root.right==null) return 1+minDepth(root.left);

if(root.left==null) return 1+minDepth(root.right);

return Math.min(minDepth(root.left),minDepth(root.right))+1;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值