码迷,mamicode.com
首页 > 其他好文 > 详细

Lintcode155-Minimum Depth of Binary Tree-Easy

时间:2019-04-09 12:36:45      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:end   else   nbsp   ==   init   div   nod   oid   body   

155. Minimum Depth of Binary Tree

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.

Example

Example 1:

Input: {}
Output: 0

Example 2:

Input:  {1,#,2,3}
Output: 3	
Explanation:
	1
	 \ 
	  2
	 /
	3    

 

 
注意:
如果用普通的递归,那么在helper方法之前要考虑只有一边树的情况(根结点+右子树 root.left == null && root.right != null /跟节点+左子树 root.right == null && root.left != null )。一定要加&&,否则input为{2}(只有跟节点时)也会进入这个case。如果不考虑一边树的话,会误判左子树的长度为1,那么会minDepth会返回1.
递归法代码:
/**
 * 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
     */
    int minDepth = Integer.MAX_VALUE;
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        } else if (root.left == null && root.right != null) {
            helper(root.right, 2);
        } else if (root.right == null && root.left != null) {
            helper(root.left, 2);
        } else {
            helper(root, 1);
        }
        return minDepth;
    }
    public void helper(TreeNode root, int curDepth) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            if (curDepth < minDepth) {
                minDepth = curDepth;
            }
            return;
        }
        
        helper(root.left, curDepth + 1);
        helper(root.right, curDepth + 1);
    }
}

 

二分法:
public class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return getMin(root);
    }

    public int getMin(TreeNode root){
        if (root == null) {
            return Integer.MAX_VALUE;
        }

        if (root.left == null && root.right == null) {
            return 1;
        }

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

 

 

Lintcode155-Minimum Depth of Binary Tree-Easy

标签:end   else   nbsp   ==   init   div   nod   oid   body   

原文地址:https://www.cnblogs.com/Jessiezyr/p/10676068.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!