您的位置:首页 > 编程语言 > Go语言

【第一周algorithm1】-minimum-depth-of-binary-tree

2017-07-13 00:03 381 查看
=============算法题目=============

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

=================================

递归(DFS):

方法1:

public int run(TreeNode root) {
//1:空结点
if (root == null)
return 0;
//2:左右子树都为空,返回root的深度为1
if (root.left == null && root.right == null)
return 1;
//3:左或者右子树为空,则返回相应的非空子树最小值+1
if (root.left == null && root.right != null)
return 1 + run(root.right);
if (root.right == null && root.left != null)
return 1 + run(root.left);
//4:如果左右子树都不为空,则返回左右子树中最小值
return Math.min(run(root.left) + 1, run(root.right) + 1);
}


方法2:

public int run(TreeNode root) {
//1:空结点
if (root == null)
return 0;
//2:左右子树都为空或者有一个非空的情况,返回root的深度为1
int l = run(root.left);
int r = run(root.right);
if (l == 0 || r == 0)
return l + r + 1;
//3:如果左右子树都不为空,则返回左右子树中最小值
return Math.min(l, r) + 1;
}


迭代(BFS):

方法1:

public int runLevelTraverse(TreeNode root){
//1:如果树为空,返回0
if (root == null)
return 0;
//2:如果只有一个根结点,返回1(此处可去掉,因为此处包含在下面)
if (root.right == null && root.left == null)
return 1;
//3:否则,用层次遍历来寻找第一个leaf node ,则为最短路径
int depth = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()){
int size = queue.size();
depth++;
for (int i = 0; i < size; i++){
TreeNode curNode = queue.poll();
if (curNode.left == null && curNode.right == null)
return depth;
if (curNode.left != null)
queue.offer(curNode.left);
if (curNode.right != null)
queue.offer(curNode.right);
}
}
return 0;
}


方法2:

public int runLevelTraverse(TreeNode root){
//1:如果树为空,返回0
if (root == null)
return 0;
//2:否则,用层次遍历来寻找第一个leaf node ,则为最短路径
ArrayList<TreeNode> list = new ArrayList<>();
//根入队列,此处使用arrayList模拟队列功能
list.add(root);
int depth = 1;
//curr指向当前层的第一个结点,last指向下一层的第一个结点
int cur = 0, last;
while (cur < list.size()){
last = list.size();
//遍历当前层,如果有叶子结点则返回depth,否则depth+1继续遍历
while (cur < last){
TreeNode curNode = list.get(cur);
if (curNode.left == null && curNode.right == null)
return depth;
if (curNode.left != null)
list.add(curNode.left);
if (curNode.right != null)
list.add(curNode.right);
cur++;
}
depth++;
}
return depth;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息