Minimum Depth of Binary Tree
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 a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
return minDepth(root, 1);
}
public int minDepth(TreeNode root, int depth) {
if(root == null) return 0;
if(root.left != null && root.right != null)
return Math.min(minDepth(root.left, depth + 1), minDepth(root.right, depth + 1));
if(root.left != null && root.right == null)
return minDepth(root.left, depth + 1);
if(root.left == null && root.right != null)
return minDepth(root.right, depth + 1);
return depth;
}
}
最长路径:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}