题解 | #牛群排列的最大深度#
牛群排列的最大深度
https://www.nowcoder.com/practice/b3c6383859a142e9a10ab740d8baed88
知识点
树,深度遍历
解题思路
树的最大深度等于左右子树深度的最大值,而某个节点的深度等于父节点的深度加一。
因此可以递归进行树的深度遍历,找到每个叶子节点的深度返回给父节点,父节点取到左右子树深度的最大值再返回给它的父节点,最后放回给根节点的就是整个树的最大深度。
Java题解
import java.util.*;
/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int maxDepth (TreeNode root) {
        // write code here
        return fun(root,0);
    }
    public int fun(TreeNode root,int pre){
        int ans = pre + 1;
        if(root.left != null){
            ans = Math.max(ans,fun(root.left,pre + 1));
        }
        if(root.right != null){
            ans = Math.max(ans,fun(root.right,pre + 1));
        }
        return ans;
    }
}
查看9道真题和解析

