二叉树的深度
两者的初始值不一致,因为二叉树最小深度求最小值,所以找到无子节点情况就返回depth,这个时候没有经过自增,但是二叉树最大深度求最大值的情况就一定会经过depth的自增,也就是找到没有子节点的情况后,depth还会自增1.所以初始要为0才是正确的。
二叉树的最小深度
//二叉树的最小深度 public int minDepth(TreeNode root) { if (root == null) return 0; Queue<TreeNode> q = new LinkedList<>(); q.offer(root); // root 本⾝就是⼀层,depth 初始化为 1 int depth = 1; while (!q.isEmpty()) { int sz = q.size(); /* 将当前队列中的所有节点向四周扩散 */ for (int i = 0; i < sz; i++) { TreeNode cur = q.poll(); /* 判断是否到达终点 */ if (cur.left == null && cur.right == null) return depth; /* 将 cur 的相邻节点加⼊队列 */ if (cur.left != null) q.offer(cur.left); if (cur.right != null) q.offer(cur.right); } /* 这⾥增加步数 */ depth++; } return depth; }
二叉树的最大深度
//二叉树的最大深度 public int maxDepth(TreeNode root) { if (root == null) return 0; Queue<TreeNode> q = new LinkedList<>(); q.offer(root); int depth = 0; while (!q.isEmpty()) { int sz = q.size(); for (int i = 0; i < sz; i++) { /* 将当前队列中的所有节点向四周扩散 */ TreeNode cur = q.poll(); /* 将 cur 的相邻节点加⼊队列 */ if (cur.left != null) q.offer(cur.left); if (cur.right != null) q.offer(cur.right); } /* 这⾥增加步数 */ depth++; } return depth; }

浙公网安备 33010602011771号