编号104:二叉树的最大深度

编号104:二叉树的最大深度

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

图片

返回它的最大深度 3 。

思路

递归实现:先找左子树的最大深度;再找右子树的最大深度,深度为其中最大的+1(头节点)

层序遍历:遍历到每层深度+1

代码

//递归实现
public static int getDepth(Node root){
        if(root == null){
            return 0;
        }
        int leftDepth = getDepth(root.left);//左
        int rightDepth = getDepth(root.right);//右
        int depth = Math.max(leftDepth,rightDepth)+1;//中
        return depth;
    }
//层序遍历
public static int getDepth1(Node root){
        int dempth = 0;
        if(root == null){
            return 0;
        }
        Queue<Node> queue = new ArrayDeque();
        queue.add(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            dempth++;
            for (int i = 0; i < size ; i++) {
                Node temp = queue.poll();
                if(temp.left!=null){
                    queue.add(temp.left);
                }
                if(temp.right!=null){
                    queue.add(temp.right);
                }
            }
        }
        return dempth;
    }

posted @ 2021-04-03 17:09  胡木杨  阅读(56)  评论(0)    收藏  举报