一、题目粗心
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长门路上的节点数。
阐明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
起源:力扣(LeetCode)
链接:https://leetcode.cn/problems/...
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
二、解题思路
思路:求二叉树的最大深度问题用深度优先搜寻 Depth First Search,递归的完满利用。
思路二:也能够用层序遍历二叉树,而后计数总层数,即为二叉树的最大深度,须要留神的是while循环中的for循环的写法,肯定要将q.size()放在初始化里,而不能放在普快进行的条件中,因为q的大小是随时变动的,所以放在进行条件中会出错。
三、解题办法
3.1 Java实现-递归
/** * Definition for a binary tree node. * 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; * } * } */class Solution { public int maxDepth(TreeNode root) { if (root == null) { return 0; } return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; }}
3.2 Java实现-层序遍历
public class Solution2 { public int maxDepth(TreeNode root) { if (root == null) { return 0; } int ans = 0; Queue<TreeNode> q = new LinkedList<>(); q.offer(root); while (!q.isEmpty()) { ans++; for (int i = q.size(); i > 0; i--) { TreeNode t = q.poll(); if (t.left != null) { q.offer(t.left); } if (t.right != null) { q.offer(t.right); } } } return ans; }}
四、总结小记
- 2022/9/5 做开发没有需要设计那就是无穷劫难的开始