二叉树的最大深度与最小深度

来源:互联网 发布:java垃圾自动回收 编辑:程序博客网 时间:2024/05/18 03:02

求二叉树的最小深度与最大深度,都是用递归的方法实现。

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.

实现代码:

public class Solution {    public int minDepth(TreeNode root) {        if(root == null)            return 0;                    int left=minDepth(root.left);        int right=minDepth(root.right);                if(left==0)  //如果左子树为空,则返回右子树深度            return right+1;        if(right==0) //如果右子树为空,则返回左子树深度            return left+1;                return left<right ? left+1:right+1;    }}

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

public class Solution {    public int maxDepth(TreeNode root) {           if (root == null)             return 0;    return (Math.max(maxDepth(root.left)+1, maxDepth(root.right)+1));    }}




0 0
原创粉丝点击