首页 > 代码库 > [LeetCode] 104. Maximum Depth of Binary Tree Java

[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