天天看點

Leetcode初學——二叉樹的最大深度

題目:

Leetcode初學——二叉樹的最大深度

分析:

回溯法在解二叉樹問題中真的是非常好用了

代碼:

class Solution {
    int max=0;
    public int maxDepth(TreeNode root) {
        help(root,0);
        return max;
    }
    public void help(TreeNode root,int count){
        if(root!=null) count++;
        else return;
        if(root.left!=null){
            help(root.left,count);
        }
        if(root.right!=null){
            help(root.right,count);
        }
        if(root.left==null && root.right==null){
            max=Math.max(max,count);
            return;
        }
    }
}
           

結果:

Leetcode初學——二叉樹的最大深度