新手算法学习之路----二叉树(二叉树的最大深度)

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
     //First Version
    // public int maxDepth(TreeNode root) {
    //     // write your code here
    //     if(root == null) return 0;
    //     int left = helper(root.left);
    //     int right = helper(root.right);
    //     return Math.max(left,right)+1;
        
    // }
    // public int helper(TreeNode root){
    //     if(root == null){
    //         return 0;
    //     }else {
    //       return Math.max(helper(root.left),helper(root.right))+1;
    //     }
    // }
    
    //Second Version
    // public int maxDepth(TreeNode root){
    //     if(root==null){
    //         return 0;
    //     }
    //     int left = maxDepth(root.left);
    //     int right = maxDepth(root.right);
    //     return Math.max(left,right)+1;
    // }
    
    //Traverse                       红色字体是关键部位
    private int depth;     ***这个depth是一个全局变量
    public int maxDepth(TreeNode root) {
        depth=0;
        if(root == null){
            return 0;
        }
        helper(root, 1);
        return depth;
    }
    
    private void helper(TreeNode root, int depth_h){
        if(root == null){
            return;
        }
        if(depth_h>depth){
            depth = depth_h;
        }
        helper(root.left, depth_h+1);
        helper(root.right,depth_h +1);
    }
    
}

 

posted @ 2017-07-12 09:18  JunLiu37  阅读(137)  评论(0编辑  收藏  举报