二叉树的最小深度 二叉树

watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2tldmluX25hbg==,size_16,color_FFFFFF,t_70

https://www.bilibili.com/video/av46402848/

第一种解题方法

/**
 * 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.left==null)
		return minDepth(root.right)+1;   //!!!!!关键 左子树为null 就看 右子树
	if(root.right==null)
		return minDepth(root.left)+1;    //!!!!!关键 右子树为null 就看 左子树
	 int left  = minDepth(root.left)  +1;
	 int right = minDepth(root.right) +1;
	 return Math.min(left,right);            //!!!!!关键
    }
}

第二种用链表实现 层次遍历 

class Solution {
	public int minDepth(TreeNode root) {
		int res = 0;
		if (root == null)
			return res;
		LinkedList<TreeNode> ll = new LinkedList<TreeNode>();
		ll.add(root);
		while (!ll.isEmpty()) {
			int size = ll.size();
			res++;                                                 // 要用两个while 的原因主要是增加层作用
			while (size > 0) {
				TreeNode temp = ll.poll();
				if (temp.left == null && temp.right == null)
					return res;
				if (temp.right != null)
					ll.add(temp.right);
				if (temp.left != null)
					ll.add(temp.left);
				size--;
			}
		}
		return res;
	}
}


猜你喜欢

转载自blog.51cto.com/14429166/2416564
今日推荐