二叉树最大深度-层遍历实现

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

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

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

		public TreeNode(int val) {
			this.val = val;
		}
	}

	public int maxDepth(TreeNode head) {
		if (head == null) {
			return 0;
		}
		Queue<TreeNode> queue = new LinkedList<>();
		queue.offer(head);
		TreeNode last = head;
		TreeNode nlast = null;
		int res = 0;
		while (!queue.isEmpty()) {
			head = queue.poll();
			if (head.left != null) {
				queue.offer(head.left);
				nlast = head.left;
			}
			if (head.right != null) {
				queue.offer(head.right);
				nlast = head.right;
			}
			if (last == nlast && !queue.isEmpty()) {
				last = nlast;
				nlast = null;
				res++;
			}
		}
		return res;
	}
}

猜你喜欢

转载自blog.csdn.net/gkq_tt/article/details/88699469