代码随想录-刷题笔记
104. 二叉树的最大深度 - 力扣(LeetCode)
内容:
本题较为基础,可以说是深搜的入门款,深搜的具体知识点请看
图论-表示形式&深度优先搜索-CSDN博客这篇文章
当然二叉树肯定不会跟通用的深搜模板一样那么复杂,只需要处理左右两个子树即可.
对于二叉树分为三种遍历方式
二叉树的前序遍历求深度 - 深度是从根节点开始算,一直到叶子节点
二叉树的后序遍历求高度 - 高度是从叶子节点开始算,一直到根节点
这二者很重要.
但是因为二叉树的最大深度实际上和高度是完全相等的。至此我们这道题使用后序遍历。
代码如下:
/*** 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 dfs(TreeNode cur , int depth) {if(cur.left == null && cur.right == null) {return depth;}int leftDepth = 0;int rightDepth = 0;if(cur.left != null) leftDepth = dfs(cur.left , depth+1);if(cur.right != null) rightDepth = dfs(cur.right , depth+1);return Math.max(leftDepth,rightDepth); //求左右深度的最大值}public int maxDepth(TreeNode root) {if(root == null) return 0;return dfs(root,1);}
}
这里写的是求深度,但是实际上是求高度,这点千万别搞错
总结:
二叉树求深度使用前序遍历,因为需要先记录节点再去进行搜索
求高度正好反之,因此使用后序遍历