题解 | #牛群的最大高度#
牛群的最大高度
https://www.nowcoder.com/practice/f745023c5ac641c9914a59377dacdacf
考察二叉树遍历,先序遍历。
本质是在先序遍历的过程中需要找到最大的值,用到递归
终止条件是到空指针的时候一层层return,每层找到的值和val进行比较,用val记录得到最终的最大值
所以使用递归左右子树中遍历,取到的值进行比较,更新最大值val,最后输出val即为所求!
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 findMaxHeight (TreeNode root) { // write code here if(root==null) return 0; int val = root.val; return Math.max(val,Math.max(findMaxHeight(root.left),findMaxHeight(root.right))); } }