[Leetcode-Tree]Maximum / Minimum Depth of Binary Tree

Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.node

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.rest

1.解題思路 code

用遞歸實現很簡單,對於每一個根節點,最大深度就等於左子樹的最大深度和右子樹的最大深度的較大值。htm

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

Minimum Depth of Binary Tree遞歸

Given a binary tree, find its minimum depth.it

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.io

1.解題思路class

本題的注意點在於若是某個根節點有一邊的子樹爲空,那麼它的深度就等於另外一邊不爲空的子樹的深度,其餘的邏輯與上一題相同。test

2.代碼im

public class Solution {
    public int minDepth(TreeNode root) {
        if(root==null) return 0;
        if(root.left==null&&root.right!=null) 
            return minDepth(root.right)+1;
        if(root.right==null&&root.left!=null)
            return minDepth(root.left)+1;
        int leftmin=minDepth(root.left);
        int rightmin=minDepth(root.right);
        return Math.min(leftmin,rightmin)+1;
    }
}
相關文章
相關標籤/搜索