剑指Offer面试题55-1:二叉树的深度

很简单的一道题,答案的没有用全局变量,更好

class Solution {
    int max_dep=0;
    public int maxDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        findDepth(root,1);
        return max_dep;
    }

    public void findDepth(TreeNode root,int cur_dep){
        if(cur_dep > max_dep){
            max_dep = cur_dep;
        }
        if(root.left!=null){
            findDepth(root.left,cur_dep+1);
        }

        if(root.right!=null){
            findDepth(root.right,cur_dep+1);
        }
    }
}

答案

public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }

猜你喜欢

转载自blog.csdn.net/qq_40473204/article/details/115000349