Sword Finger-Simple-Depth of Binary Tree

Question description

Input a binary tree and find the depth of the tree. The nodes (including root and leaf nodes) passing through in sequence from the root node to the leaf nodes form a path of the tree. The length of the longest path is the depth of the tree.

Ideas

There are two solutions: post-order traversal (DFS) and layer-order traversal (BFS).

code

1. Recursion (DFS)/Postorder
The relationship between the depth of the tree and the depth of its left (right) subtree. Obviously, the depth of this tree is equal to the maximum of the depth of the left subtree and the depth of the right subtree + 1.

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

2. Level-order traversal (BFS): implemented using queues.
Each time a layer is traversed, the counter is +1 until the traversal is completed, and the depth of the tree can be obtained.

class Solution {
    
    
    public int maxDepth(TreeNode root) {
    
    
        if(root == null) return 0;
        List<TreeNode> queue = new LinkedList<>() {
    
    {
    
     add(root); }}, tmp;
        int res = 0;
        while(!queue.isEmpty()) {
    
    
            tmp = new LinkedList<>();
            for(TreeNode node : queue) {
    
    
                if(node.left != null) tmp.add(node.left);
                if(node.right != null) tmp.add(node.right);
            }
            queue = tmp;
            res++;
        }
        return res;
    }
}

Guess you like

Origin blog.csdn.net/qq_32301683/article/details/108362570