树的深度

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    // private int max;
    
    // public int maxDepth(TreeNode root) {
    //     // write your code here
    //     if(root == null)
    //         return 0;
    //     max = 0;
    //     traverse(root, 1);
    //     return max;
    // }
    
    // void traverse(TreeNode root, int depth)
    // {
    //     if(root == null)
    //         return;
        
    //     max = Math.max(max, depth);
    //     traverse(root.left, depth+1);
    //     traverse(root.right, depth+1);
    // }
    
    public int maxDepth(TreeNode root) {
        // write your code here
        if(root == null)
            return 0;
            
        int dl = maxDepth(root.left);
        int dr = maxDepth(root.right);
      
        return Math.max(dl, dr)+1;
    }
    
}

  

原文地址:https://www.cnblogs.com/ya-cpp/p/11191343.html