The sword refers to Offer 55-I. The depth of the binary tree---recursion/breadth traversal

Sword refers to Offer 55-I. The depth of the binary tree

Method one: recursion

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

Method 2: Breadth Traversal (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;
    }
}

 

Guess you like

Origin blog.csdn.net/qq_41041762/article/details/108083963