美文网首页
二叉树深度递归与非递归

二叉树深度递归与非递归

作者: 啦啦哇哈哈 | 来源:发表于2018-11-12 03:30 被阅读0次

二叉树的最大深度

下面给出递归算法,非递归只需要在层序遍历的基础上进行改造就可以了。

    public int maxDepth(TreeNode root) {
            if(root == null){
                return 0;
            }
            if(root.right == null){
                return maxDepth(root.left) + 1;
            }
            if(root.left == null){
                return maxDepth(root.right) + 1;
            }
            
            return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
    }

二叉树的最小深度

  • 递归
        public int MinDepth(TreeNode root) {
            if(root == null){
                return 0;
            }
            if(root.left == null){
                    return MinDepth(root.right) + 1;
                }
                if(root.right == null){
                    return MinDepth(root.left) + 1;
                }

            return Math.min(MinDepth(root.left),MinDepth(root.right)) + 1;
        }
  • 非递归
    还是基于层序遍历,加一个depth变量,中间过程遇到叶子节点了直接return depth
    public int minDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 1;
        while(!queue.isEmpty()){
            int l = queue.size();
            while(l -- > 0){
                TreeNode node = queue.poll();
                if(node.left == null && node.right == null){
                    return depth;
                }
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
            depth ++;
        }        
        return depth;
    }

N叉树的最大深度

    public int maxDepth(Node root) {
        if(root == null){
            return 0;
        }
        
        int max = 0;
        for(Node node : root.children){
            int depth = maxDepth(node);
            if(max < depth){
                max = depth;
            }
        }
        
        return max + 1;
    }

相关文章

  • 总结

    1、二叉树广度遍历(非递归) 广度遍历非递归实现需要依靠一个队列。 2、二叉树深度遍历(递归与非递归,前序,中序和...

  • 二叉树的遍历实现递归与非递归

    本文实现了二叉树的深度遍历算法,分为递归与非递归 递归的实现非常简单,基本上没啥难度 非递归的实现需要根据遍历的顺...

  • 二叉树的前序、中序、后序遍历(递归、非递归)

    二叉树 前序 递归: 非递归: 中序 递归: 非递归: 层序 递归: 非递归:

  • 二叉树深度递归与非递归

    二叉树的最大深度 下面给出递归算法,非递归只需要在层序遍历的基础上进行改造就可以了。 二叉树的最小深度 递归 非递...

  • Java 二叉树递归与非递归所有遍历

    二叉树的递归与非递归遍历 PS:非递归遍历搞得头脑发晕.... 参考文献 :左神的书

  • 大数据面试题目

    一、数据结构与算法 1.二叉树前序、中序、后续遍历方式(递归以及非递归) 2.二叉树的深度以及广度遍历方式 ...

  • 5. 深度优先、广度优先

    1. 二叉树的深度优先遍历和广度优先遍历2. 深度优先搜索递归和非递归实现 深度优先(DFS):前序遍历 广度优先...

  • 算法之二叉树

    二叉树之C++实现 创建二叉树 复制二叉树 先序遍历 递归实现 非递归实现 中序遍历 递归实现 非递归实现 后序遍...

  • 面试,你需要知道这些东西

    一、数据结构与算法 1.二叉树前序、中序、后续遍历方式(递归以及非递归) 2.二叉树的深度以及广度遍历方式 3.二...

  • 新鲜出炉!阿里大数据工程师面经!

    一、数据结构与算法 1.二叉树前序、中序、后续遍历方式(递归以及非递归) 2.二叉树的深度以及广度遍历方式 3.二...

网友评论

      本文标题:二叉树深度递归与非递归

      本文链接:https://www.haomeiwen.com/subject/utpoxqtx.html