剑指 Offer 55 - I. 二叉树的深度---递归/广度遍历

剑指 Offer 55 - I. 二叉树的深度

方法一: 递归

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

方法二: 广度遍历(Queue)

class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)  return 0;
        Queue<TreeNode> q=new LinkedList<>();
        q.add(root);
        int res=0;
        while(!q.isEmpty()){
            int size=q.size();
            for(int i=0;i<size;i++){
                TreeNode node=q.poll();
                if(node.left!=null) q.add(node.left);
                if(node.right!=null)    q.add(node.right);
            }
            res++;
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41041762/article/details/108083963