剑指 Offer 55. 二叉树的深度

题目链接

https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/

题目描述

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

例如:

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

返回它的最大深度 3 。

解题思路以及AC代码

参考:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/solution/mian-shi-ti-55-i-er-cha-shu-de-shen-du-xian-xu-bia/

1 递归解法

核心思路:每个节点的深度与它左右子树的深度有关,且等于其左右子树最大深度值加上 1

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

2 利用层序遍历

核心思路:可以把树看成一层一层,利用层序遍历算法(BFS),每当遍历完一层即高度加一

  • 树的层序遍历 / 广度优先搜索往往利用 队列 实现。
  • 关键点: 每遍历一层,则计数器 +1+1 ,直到遍历完成,则可得到树的深度。
public Solution{
    public int maxDepth(TreeNode root){
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int ans = 0;
        while(!queue.isEmpty()){
            ans++;
            int size = queue.size();
            // 不能在for循环里面直接利用queue.size()替代size,因为循环过程中队列的大小在动态变化
            for(int i = 0; i < size; i++){
                TreeNode node = queue.poll(); //移除并返回队列头部元素
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
        }
        return ans;
    }
}
posted @ 2020-07-24 23:46  控球强迫症  阅读(156)  评论(0编辑  收藏  举报