ソードフィンガーオファーインタビュー質問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