剑指offer:二叉树的深度

题意描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

解题思路

一、递归

首先判断当前节点是否为空,为空则返回0

然后进入左右子树的递归,左右子树返回值中的最大值+1,就是当前二叉树的深度。

    public int TreeDepth(TreeNode root) {
    	if(root == null) return 0;	//当前节点为空	
        int left = TreeDepth(root.left);	//左子树进入递归
        int right = TreeDepth(root.right);	//右子树今日递归
        return  Math.max(left,right)+1;	//返回两者最大值+1
    }

二、非递归

使用LinkedList构建一个队列。

第一层循环用来判断当前队列中是否还存在节点,存在说明当前层还存在子节点。

第二层循环用来弹出当前层的节点,并把当前层节点的子节点入队列,每弹出一个节点size --

public int TreeDepth(TreeNode root) {
        if(root == null) return 0;	
        Queue<TreeNode> queue = new LinkedList<>();	//LinkedList构建队列
        queue.add(root);	//根节点入队列
        int dep = 0;	//深度
        int size = 0;	
        while(!queue.isEmpty()){	//队列不为空,说明当前二叉树还存在子节点
            dep ++;   //深度+1
            size = queue.size();	//size记录同层的节点数量
            while(size>0){	//将同层节点出队列,节点的孩子入队列
                root = queue.poll();	//出队列
                if(root.left != null) queue.add(root.left);	//左子树不为空
                if(root.right != null) queue.add(root.right);//右子树不为空
                size--;
            }
        }
        return dep;
    }
posted @ 2020-04-16 22:41  灵图  阅读(122)  评论(0)    收藏  举报