111 title: minimum depth of a binary tree

One. Problem Description

Given a binary tree, to find out the minimum depth.

Minimum depth is the number of nodes in the shortest path from the root node to leaf nodes nearest.

Description: leaf node is a node has no child nodes.

Example:

Given binary tree [3,9,20, null, null, 15,7],

    3

   / \

  9  20

      /  \

   15   7

2 returns to its minimum depth.

two. Problem-solving ideas

This topic and ideas: the use of depth-first traversal + recursively solved.

Step a: Construction of a recursive function (root), bottom-up fashion, starting with the leaf nodes is determined, to find the minimum depth.

Step two: on one node is then recursively determines the minimum depth of the node in which the left and right subtree, recursively repeated, eventually returning lowermost depth.

three. Results of the

When execution: 0 ms, defeated 100.00% of users in all java submission

Memory consumption: 37.6 MB, defeated 56.49% of all users in java submission

four. Java code

class Solution {
    public int minDepth(TreeNode root) {
        if(root==null) {
           return 0;
       }else {
           return getTree(root);
       }
    }
    public int getTree(TreeNode root) {
        int leftnum=1,rightnum=1;
        
        if(root.left!=null) {
            leftnum=getTree(root.left)+1;
        }
        if(root.right!=null) {
            rightnum=getTree(root.right)+1;
        }
        if(root.left!=null&&root.right!=null) {
            return Math.min(leftnum, rightnum);
        }else {
            return Math.max(leftnum, rightnum);
        }
        
    }
}

 

Guess you like

Origin www.cnblogs.com/xiaobaidashu/p/11842160.html