leetcode---tree topic

Problem 1: Find the maximum depth of a binary tree 

Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
// find the maximum depth of the binary tree
public class Solution {
    public int maxDepth(TreeNode root) {
        if(root==null)          
            return 0;
        int lDepth= maxDepth(root.left);
        int rDepth= maxDepth(root.right);
        return 1+( lDepth>rDepth ? lDepth: rDepth); //The left and right subtrees choose the one with the largest depth (even if there is no node on one side, it doesn't matter, the largest one has nothing to do with 0)
    }
}


Topic 2: Find the minimum depth of a binary tree (need to consider the case of no child nodes on one side)

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int run(TreeNode root) {   
        if(root==null)
            return 0;
        int lDepth=run(root.left);
        int rDepth=run(root.right);
        if(lDepth==0 || rDepth==0) //Need to consider the case that there may be no child nodes on one side, so the smallest is 0, but only the root node cannot be regarded as the shortest path to the leaf node
            return lDepth+rDepth+1;
        return 1+(lDepth< rDepth? lDepth: rDepth);
    }
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325816559&siteId=291194637