怎样开网站卖东西,龙华网站制作公司,wordpress表格,苏州网站建设-中国互联本文是力扣LeeCode-104. 二叉树的最大深度 学习与理解过程#xff0c;本文仅做学习之用#xff0c;对本题感兴趣的小伙伴可以出门左拐LeeCode。
给定一个二叉树 root #xff0c;返回其最大深度。 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。 示例…本文是力扣LeeCode-104. 二叉树的最大深度 学习与理解过程本文仅做学习之用对本题感兴趣的小伙伴可以出门左拐LeeCode。
给定一个二叉树 root 返回其最大深度。 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。 示例 1 输入root [3,9,20,null,null,15,7] 输出3 示例 2 输入root [1,null,2] 输出2 提示 树中节点的数量在 [0, 104] 区间内。 -100 Node.val 100 思路
做二叉树的题目首先需要确认的是遍历顺序这道题可以用后序遍历左右中也可以用前序遍历中左右笔者这里采用后序遍历因为理解和书写更适合刷题宝宝。
确定递归函数的参数和返回值: int getDepth(TreeNode node)确定终⽌条件: if(nodenull)return 0;确定单层递归的逻辑: int leftHeight getDepth(node.left); //左int rightHeight getDepth(node.right); //右int height 1Math.max(leftHeight,rightHeight); //中return height;代码实现
class Solution {public int maxDepth(TreeNode root) {return getDepth(root);}private int getDepth(TreeNode node){if(nodenull)return 0; //遇到叶子结点返回int leftHeight getDepth(node.left); //递归返回遍历到当前节点node的左子树的深度int rightHeight getDepth(node.right); //递归返回遍历到当前节点node的右子树的深度int height 1Math.max(leftHeight,rightHeight); //取当前节点下最深的左子树或右子树并1(当前节点)return height;}
}优化代码实现
class Solution {public int maxDepth(TreeNode root) {if(rootnull)return 0;return 1Math.max(maxDepth(root.left),maxDepth(root.right));}
}最终要的一句话做二叉树的题目首先需要确认的是遍历顺序
大佬们有更好的方法请不吝赐教谢谢