您好,欢迎来到[编程问答]网站首页   源码下载   电子书籍   软件下载   专题
当前位置:首页 >> 编程问答 >> C/C++ >> 问一下一个数据结构的简单题目,有关树和递归 ,自己画了个图,还是不明白。。谢谢!!!。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

问一下一个数据结构的简单题目,有关树和递归 ,自己画了个图,还是不明白。。谢谢!!!。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

来源:网络整理     时间:2016/8/29 1:28:59     关键词:

关于网友提出的“ 问一下一个数据结构的简单题目,有关树和递归 ,自己画了个图,还是不明白。。谢谢!!!。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。”问题疑问,本网通过在网上对“ 问一下一个数据结构的简单题目,有关树和递归 ,自己画了个图,还是不明白。。谢谢!!!。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:

问题: 问一下一个数据结构的简单题目,有关树和递归 ,自己画了个图,还是不明白。。谢谢!!!。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
描述:

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:

引用 3 楼 klmn111aaa 的回复:
Quote: 引用 1 楼 czarten 的回复:

是返回2没错啊
你的疑问在哪里?
这个返回值2就是根节点的leftdepth
而根节点的rightdepth等于1,你图上也写了
然后return leftdepth > rightdepth ? rightdepth + 1 : leftdepth + 1,因为leftdepth > rightdepth成立,所以结果是rightdepth+1=2

也就是说对于最底一层都会先执行
if (leftdepth == 0){  
            return rightdepth+1;  
        }  
对于只有左或右子叶的 执行
if (leftdepth == 0){  
            return rightdepth+1;  
        }  
        if (rightdepth == 0){  
            return leftdepth+1;  
        } 
对于左右都有的才执行 return leftdepth > rightdepth ? rightdepth + 1 : leftdepth + 1 
是这个意思吧?

当然。函数遇return就结束了,后面都不用运行了
以上介绍了“ 问一下一个数据结构的简单题目,有关树和递归 ,自己画了个图,还是不明白。。谢谢!!!。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/3647064.html

相关图片

相关文章