知识点
树,递归
解题思路
定义当前节点的值就是最大值。
如果当前节点有左子树,我们就用同样的方法去查左子树的最大值和当前最大值比较。
如果当前节点有右子树,我们也先去查右子树最大值和目前最大值比较。
最终得到最大值返回。
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 findMaxHeight (TreeNode root) { // write code here int ans = root.val; if(root.left != null){ ans = Math.max(ans,findMaxHeight(root.left)); } if(root.right != null){ ans = Math.max(ans,findMaxHeight(root.right)); } return ans; } }