LeetCode之111. 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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its minimum depth = 2.

自己的代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public static int minDepth(TreeNode root) {
		if(root == null) return 0;
		int[] result = new int[1];
		result[0] = Integer.MAX_VALUE;
		
		depthHelper(root,1,result);

		return result[0];
	}

	public static void depthHelper(TreeNode root,int depth,int[] result) {
		if(root != null && root.left == null && root.right == null) {
			if( depth

小结:

a)注意进行指针的非空验证

b)注意,判断一定要为叶子节点,叶子节点的条件是:root != null && root.left == null && root.right == null

 

别人的代码:

方法1:递归(也是DFS的思想)

public class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1;
 
    }
}

小结:

a)核心就在切分子问题,二叉树天生就是可以很好的切分成子问题来处理的;

b)体会left + right + 1,这个手法的妙处

//This is not very intuitive especially left + right + 1, my readable code on my post:

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) return 0;
        
        // leaf node
        if(root.left == null && root.right == null) return 1;
        
        // leaf nodes are in right subtree
        if(root.left == null) return minDepth(root.right) + 1;
        
        // leaf nodes are in left subtree
        if(root.right == null) return minDepth(root.left) + 1;
 
        // left/right subtrees both contains leaf nodes
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        return Math.min(left, right) + 1;
    }
}

 

方法2:BFS

/** Solution 2: BFS level order traversal */
public int minDepth2(TreeNode root) {
    if (root == null) {
        return 0;
    }
    Queue queue = new LinkedList<>();
    queue.offer(root);
    int level = 1;
    while (!queue.isEmpty()) {
        int size = queue.size();
        for (int i = 0; i < size; i++) {
            TreeNode curNode = queue.poll();
            if (curNode.left == null && curNode.right == null) {
                return level;
            }
            if (curNode.left != null) {
                queue.offer(curNode.left);
            }
            if (curNode.right != null) {
                queue.offer(curNode.right);
            }
        }
        level++;
    }
    return level;
}

小结:

a)也就是使用二叉树层序遍历的模板代码,再增加了一个level的局部变量,记录当前遍历到了树的第几层

 

 

 

 

 

你可能感兴趣的:(LeetCode刷题)