[LeetCode] 104. Maximum Depth of Binary Tree Java
阿新 • • 發佈:2017-07-18
font from max clas [] 高度 java ret 使用
題目:
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