温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

求二叉树的深度和宽度

发布时间:2020-07-21 06:18:17 来源:网络 阅读:884 作者:小止1995 栏目:编程语言

深度:

int length(BiTree t) {           int depth2 = 0;           int depth3 = 0;                      if(t == null ) return 0;           //右子树的深度           depth2 = length(t.right);           //左子树的深度           depth3 = length(t.left);                      if(depth2>depth3)               return depth2+1;           else               return depth3+1;   }

宽度:

int getMaxWidth(TreeNode root)  {      if (root == null)               return 0;              Queue<TreeNode> queue = new ArrayDeque<TreeNode>();      int maxWitdth = 1; // 最大宽度             queue.add(root); // 入队      while (true)     {        int len = queue.size(); // 当前层的节点个数        if (len == 0)                            break;                    while (len > 0)         {            // 如果当前层,还有节点                            TreeNode t = queue.pop();                             len--;                             if (t.left != null)                                     queue.push(t.left); // 下一层节点入队                            if (t.right != null)                                     queue.add(t.right);// 下一层节点入队                     }                     maxWitdth = Math.max(maxWitdth, queue.size());     }     return maxWitdth; }


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI