leetcode解题之Maximum/Minimum Depth of Binary Tree Java版(树的最大、最小深度)

104.Maximum Depth of Binary Tree

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.

Subscribe to see which companies asked this question.
  给定一棵两叉树,求它的最大深度。
  递归求解,递归公式
  f(n) = 0; n=null,
  f(n) = 1+ max(f(n左), f(n右))

public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
		}
	}
public int maxDepth(TreeNode root) {
		if (root == null)
			return 0;
		int leftDepth = maxDepth(root.left);
		int rightDepth = maxDepth(root.right);
		//左右子树的深度+1跟节点,为总深度
		return (leftDepth > rightDepth) ? (leftDepth + 1) : (rightDepth + 1);
	}

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.

注意点在于如果某个根节点有一边的子树为空,那么它的深度就等于另一边不为空的子树的深度,其他的逻辑与上一题相同。

递归

public int minDepth(TreeNode root) {
		if (root == null)
			return 0;
		// 左空,右不空
		if (root.left == null && root.right != null)
			// 返回右子树深度
			return minDepth(root.right) + 1;
		// 右空,左不空
		if (root.right == null && root.left != null)
			// 返回左子树深度
			return minDepth(root.left) + 1;
		// 否则返回左右子树的最小深度
		int leftmin = minDepth(root.left);
		int rightmin = minDepth(root.right);
		return Math.min(leftmin, rightmin) + 1;
	}

	public int minDepth(TreeNode root) {
		if (root == null)
			return 0;
		else {
			// 都不是空,返回最小值
			if (root.left != null && root.right != null)
				// 注意+1根节点深度
				return 1 + Math.min(minDepth(root.left)
						, minDepth(root.right));
			else
				// 有一个为空,则选择另外一个高度。此时有一个深度为0;
				return 1 + minDepth(root.left) + minDepth(root.right);
		}
	}

层次遍历

记录层数,当到达第一个叶结点时候就是最小深度

	public int minDepth(TreeNode root) {
		if (root == null)
			return 0;

		Queue<TreeNode> q = new LinkedList<>();
		// 使用map记录当前所处层数
		HashMap<TreeNode, Integer> map = new HashMap<>();
		q.offer(root);
		// 跟结点第一层
		map.put(root, 1);
		List<Integer> tmp = new ArrayList<>();

		while (!q.isEmpty()) {
			TreeNode node = q.poll();
			int curLevel = map.get(node);
			// 第一个到达左右子树为空的结点就是最低深度
			if (node.left == null && node.right == null)
				return curLevel;
			tmp.add(node.val);
			if (node.left != null) {
				q.offer(node.left);
				map.put(node.left, curLevel + 1);
			}
			if (node.right != null) {
				q.offer(node.right);
				map.put(node.right, curLevel + 1);
			}
		}
		return 0;
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值