剑指offer【08】- 二叉树的深度(java)

题目:二叉树的深度

考点:知识迁移能力

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

牛客网上的剑指offer题,我按从简单到难的排序来做了

 思路:从根节点出发, 查询左子树的深度 , 获取右子树的深度,比较一下,取大的,再加一 。就是整个二叉树的深度 

 

法一:递归

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public int TreeDepth(TreeNode root) {
        //递归的出口,如果节点没有值,则返回0
        if(root == null){
            return 0;
        }
        //获取左子树的最大深度
        int leftDep = TreeDepth(root.left);
        //获取右子树的最大深度
        int rigthDep = TreeDepth(root.right);
        //找出最大值,并且加上root这一层即可
        return Math.max(leftDep,rigthDep)+1;
    }
}

法二:非递归法,层次遍历法

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        int count = 0, depth = 0, nextCount = 1;
        
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        
        //将根节点添加到队列中
        queue.add(root);
        
        //第一次循环时队列的长度为1
        while(queue.size()!=0){
            count++;
            //先进先出,取出队列的第一个元素
            TreeNode top = queue.poll();
            //如果根节点的左子树不为空,则将左子树的根节点添加到队列中
            if(top.left!=null){
                queue.add(top.left);
            }
             //如果根节点的右子树不为空,则将右子树的根节点添加到队列中
             if(top.right!=null){
                 queue.add(top.right);
            }
            //当同一层的节点全部添加到队列中时,count与nextCount相等,deph+1
            if(count==nextCount){
                nextCount = queue.size();
                depth++;
                count=0;
            }
        }
        return depth;

    }
}
原文地址:https://www.cnblogs.com/linliquan/p/11171948.html