LintCode 97,155 二叉树的最小最大深度

1 二叉树的最小深度

描述

给定一个二叉树,找出其最小深度。

二叉树的最小深度为根节点到最近叶子节点的最短路径上的节点数量。

样例

样例 1:

输入: {}
输出: 0

样例 2:

输入:  {1,#,2,3}
输出: 3	
解释:
	1
	 \ 
	  2
	 /
	3    
它将被序列化为 {1,#,2,3}

样例 3:

输入:  {1,2,3,#,#,4,5}
输出: 2	
解释: 
      1
     / \ 
    2   3
       / \
      4   5  
它将被序列化为 {1,2,3,#,#,4,5}

 代码部分

 

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: The root of binary tree
     * @return: An integer
     */
    public int min(int a,int b){
        return a<b?a:b;
    }
    public int depth(TreeNode root){
        if(root==null)return 0;
        int leftminlength=depth(root.left);
        int rightminlength=depth(root.right);
        
        if(leftminlength==0&&rightminlength>0)return rightminlength+1;
        else if(rightminlength==0&&leftminlength>0)return leftminlength+1;
        else return min(leftminlength,rightminlength)+1;
    }
    public int minDepth(TreeNode root) {
        // write your code here
        return depth(root);
    }
}

补充说明

采用递归的思想。要注意的是,如果左子树为空的话,返回的是右子树的最小深度+1

如果右子树为空的话,返回的是左子树的最小深度为1

如果左右子树都存在的话,返回的是左右子树的最小深度最小值+1

 

2 二叉树的最大深度

描述

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的距离。

样例

样例 1:

输入: tree = {}
输出: 0	
样例解释: 空树的深度是0。

样例 2:

输入: tree = {1,2,3,#,#,4,5}
输出: 3
样例解释: 树表示如下,深度是3
   1
  / \                
 2   3                
    / \                
   4   5
它将被序列化为{1,2,3,#,#,4,5}

代码部分 

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    public int max(int a,int b){
        return a>b?a:b;
    }
    public int maxDepth(TreeNode root) {
        // write your code here
        if(root==null)return 0;
        int leftDepth=maxDepth(root.left)+1;
        int rightDepth=maxDepth(root.right)+1;
        return max(leftDepth,rightDepth);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值