104_二叉树的最大深度
104_二叉树的最大深度
package 二叉树.BT; import java.util.LinkedList; import java.util.Queue; /** * https://leetcode-cn.com/problems/binary-tree-level-order-traversal/submissions/ * @author Huangyujun * */ public class _104_二叉树的最大深度 { public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } //递归实现 public int maxDepth(TreeNode root) { //符合层序遍历(一层一层的遍历,递归也可以,递归也是一层往下一层) if(root == null) return 0; int height = 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); return height; } //迭代实现(需要知道当前层的遍历到了最后一个元素) public int maxDepth2(TreeNode root) { //符合层序遍历(一层一层的遍历,递归也可以,递归也是一层往下一层) if(root == null) return 0; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int height = 1; int levelSize = 1; while(!queue.isEmpty()) { //拿到当前结点 TreeNode node = queue.poll(); levelSize--; if(node.left != null) { queue.offer(node.left); } if(node.right != null) { queue.offer(node.right); } if(levelSize == 0) { height++; levelSize = queue.size(); } } return height; } }
本文来自博客园,作者:一乐乐,转载请注明原文链接:https://www.cnblogs.com/shan333/p/15709207.html