[LeetCode] 104. Maximum Depth of Binary Tree Java
Posted BrookLearnData
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 104. Maximum Depth of Binary Tree Java相关的知识,希望对你有一定的参考价值。
题目:
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
题意及分析:找出一棵树的高度,即最深子节点。使用深度遍历的方法即可,用一个变量记录遍历到当前点的最大高度,然后当前点若有子节点,遍历到子节点,那么该点的高度+1和当前的最大高度大的那个值为的当前点的子节点的最大高度。
代码:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int maxDepth(TreeNode root) { if(root==null) return 0; int[] maxDep=new int[1]; maxDep[0]=1; max(maxDep,root,1); return maxDep[0]; } public void max(int[] maxDep,TreeNode node,int height){ if(node.left!=null){ maxDep[0]=Math.max(height+1,maxDep[0]); max(maxDep,node.left,height+1); } if(node.right!=null){ maxDep[0]=Math.max(height+1,maxDep[0]); max(maxDep,node.right,height+1); } } }
以上是关于[LeetCode] 104. Maximum Depth of Binary Tree Java的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode104. Maximum Depth of Binary Tree
leetcode104-Maximum Depth of Binary Tree
Leetcode刷题记录[python]——104 Maximum Depth of Binary Tree
LeetCode 104. Maximum Depth of Binary Tree
[Lintcode]97. Maximum Depth of Binary Tree/[Leetcode]104. Maximum Depth of Binary Tree