Recursion:
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null && root.right == null) {
return 1;
}
else if (root.left != null && root.right != null) {
return 1+Math.min(minDepth(root.left), minDepth(root.right));
}
else if (root.left == null && root.right != null) {
return 1+minDepth(root.right);
} else {
return 1+minDepth(root.left);
}
}
Non-Recursion:
Why we use this method. Sometimes the tree is not balanced. This way will save lots of time. The worst of time complexity is O(n).
public int minDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
Queue<Integer> intQueue = new LinkedList<Integer>();
nodeQueue.add(root);
intQueue.add(1);
while (!nodeQueue.isEmpty()) {
TreeNode currNode = nodeQueue.poll();
int currDepth = intQueue.poll();
if (currNode.left != null) {
nodeQueue.add(currNode.left);
intQueue.add(currDepth+1);
}
if (currNode.right != null) {
nodeQueue.add(currNode.right);
intQueue.add(currDepth+1);
}
if (currNode.right == null && currNode.left == null) {
return currDepth;
}
}
return -1;//Should never reach here.
}
No comments:
Post a Comment