[Data Structures and Algorithms] seeking a minimum depth of a given binary tree. The minimum depth of the root of the tree is the number of the shortest path to the nearest node of the leaf node.

Problem-solving ideas:

At first thought is to use backtracking, the minimum depth +1 minimum depth of the tree is equal to the left and right subtrees of the tree;

According to this idea, write problem-solving algorithm

{Solution class public 
    public int RUN (the TreeNode the root) { 
        the TreeNode Node = the root; 
        
// recursive boundary condition if the current node is null height 0 
        IF (Node == null) 
           return 0; 
// recursive boundary condition if the current node is a leaf node (left and right subtrees are null), the height is. 1 
        IF (node.left == null && node.right == null) { 
            return. 1; 
        } 
// else node has left the current node value is the height (the current Look node) that is a sub-tree is not null 1+ height, therefore max       
        IF (node.left == null || node.right == null) { 
            return Math.max +. 1 (RUN (node.left), RUN (node.right)); 
        } 
        // Finally, about not empty subtree minimum height 1+ 
        return Math.min +. 1 (RUN (node.left), RUN (node.right)); 
    } 
}

 Another method is non-recursive traversal sequence, starting from the root, from the top down, using a node needs to store queue traversal,

Code:

RUN int public (the TreeNode the root) { 

        IF (the root == null) 
            return 0; 
        Queue <the TreeNode> = new new Queue the LinkedList <> (); 
        Queue.offer (the root); 

        int depth = 0; // current depth of the tree 
        while (! queue.isEmpty ()) { 
            int size = queue.size (); // this is the place, and getting the current layer need to traverse the node number 

            for (int I = 0; I <size; I ++) { 
                the TreeNode current queue.poll = (); 
                IF (current.left == null && current.right == null) // if the left and right subtrees are empty 
                    return. 1 + depth; 
                IF (! current.left = null) { 
                    Queue.offer (current.left); 
                }  
                IF (! current.right = null) {
                    Queue.offer (current.right);
                }
            }
            depth++;
        }
        return depth;
    }

  

 

Guess you like

Origin www.cnblogs.com/zhengwangzw/p/11456700.html