关于网友提出的“ 问一下一个数据结构的简单题目,有关树和递归 ,自己画了个图,还是不明白。。谢谢!!!。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。”问题疑问,本网通过在网上对“ 问一下一个数据结构的简单题目,有关树和递归 ,自己画了个图,还是不明白。。谢谢!!!。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题: 问一下一个数据结构的简单题目,有关树和递归 ,自己画了个图,还是不明白。。谢谢!!!。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
描述: 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;
if (root.left == null && root.right == null)
return 1;
int leftdepth = minDepth(root.left);
int rightdepth = minDepth(root.right);
/*当其中左右子树有一支是为null的时候,那么路径也只有另外一支了,不管多长都只能选那条路了*/ //这块不明白,
if (leftdepth == 0){
return rightdepth+1;
}
if (rightdepth == 0){
return leftdepth+1;
}
/*返回左右子树中较小的一边*/
return leftdepth > rightdepth ? rightdepth + 1 : leftdepth + 1;
}
}
解决方案1:
当然。函数遇return就结束了,后面都不用运行了
以上介绍了“ 问一下一个数据结构的简单题目,有关树和递归 ,自己画了个图,还是不明白。。谢谢!!!。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/3647064.html