Maximum Depth of Binary Tree-二叉树的最大深度

  • 求二叉树的最大深度,是常见的一种二叉树算法问题,主要解决办法有两种,一种是使用递归求解,另一种是非递归方式求解。这里给出递归求解方法。递归方法无需判断左右子树是否为空。
  • 问题来源于https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
  • Java递归求解方法:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        return Math.max(maxDepth(root.right),maxDepth(root.left))+1;
    }
}

猜你喜欢

转载自www.cnblogs.com/runs/p/9126277.html