内容简介:给予一颗二叉树,返回其树的深度。 最大深度是从根节点到最远叶节点的最长路径上的节点数。叶子是没有子节点的节点。例 :
给予一颗二叉树,返回其树的深度。 最大深度是从根节点到最远叶节点的最长路径上的节点数。
叶子是没有子节点的节点。
例 :
给予树: 3 / \ 9 20 / \ 15 7 返回深度 3.
解法
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int maxDepth(TreeNode root) { return getMaxDepth(root, 0); } public int getMaxDepth(TreeNode node, int depth) { if (node == null) { return depth; } depth++; int leftDepth = getMaxDepth(node.left, depth); int rightDepth = getMaxDepth(node.right, depth); return depth = leftDepth > rightDepth ? leftDepth : rightDepth; } }
Runtime: 0 ms, faster than 100.00% of Java online submissions for Maximum Depth of Binary Tree. Memory Usage: 38.1 MB, less than 49.96% of Java online submissions for Maximum Depth of Binary Tree.
以上所述就是小编给大家介绍的《LeetCode 104 Maximum Depth of Binary Tree》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- LeetCode 104. Maximum Depth of Binary Tree
- LeetCode 104 Maximum Depth of Binary Tree
- Leetcode PHP题解--D41 104. Maximum Depth of Binary Tree
- LeetCode - 104 - 二叉树的最大深度(maximum-depth-of-binary-tree)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Persuasive Technology
B.J. Fogg / Morgan Kaufmann / 2002-12 / USD 39.95
Can computers change what you think and do? Can they motivate you to stop smoking, persuade you to buy insurance, or convince you to join the Army? "Yes, they can," says Dr. B.J. Fogg, directo......一起来看看 《Persuasive Technology》 这本书的介绍吧!