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 minDepth(TreeNode root) {
if(root==null) {
return 0;
}
ArrayList<TreeNode> lst = new ArrayList<TreeNode>();
lst.add(root);
int depth = 1;
while(lst.size()!=0) {
ArrayList<TreeNode> tmp = new ArrayList<TreeNode>();
for(TreeNode node : lst) {
if(node.left==null && node.right==null) {
return depth;
}
if(node.left!=null) {
tmp.add(node.left);
}
if(node.right!=null) {
tmp.add(node.right);
}
}
lst = tmp;
depth++;
}
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 minDepth(TreeNode root) {
if (root == null) {
return 0;
}
LinkedList<TreeNode> fronties = new LinkedList<TreeNode>();
fronties.add(root);
int level = 1;
while (fronties.size() != 0) {
int count = fronties.size();
while (count > 0) {
TreeNode node = fronties.poll();
if (node.left != null) {
fronties.add(node.left);
}
if (node.right != null) {
fronties.add(node.right);
}
if (node.left == null && node.right == null) {
return level;
}
count--;
}
level += 1;
}
return level;
}
}
===========
/**
* 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;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
if (left == 0) {
return 1 + right;
}
if (right == 0) {
return 1 + left;
} else {
return 1 + Math.min(left, right);
}
}
}
=========
/**
* 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;
}
if (root.left == null && root.right == null) {
return 1;
} else if (root.left == null) {
return 1 + minDepth(root.right);
} else if (root.right == null) {
return 1 + minDepth(root.left);
} else {
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
}
}
没有评论:
发表评论