剑指offer - 55 - I. 二叉树的深度

题目描述

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

例如:

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

3

/
9 20
/
15 7
返回它的最大深度 3 。

提示:

节点总数 <= 10000
注意:本题与leetcode 104 题相同。

思路1:先序遍历

二叉树的深度 = 左右子树深度的较大值 + 1

代码

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

执行用时 :
0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗 :
39.6 MB, 在所有 Java 提交中击败了100.00%的用户

思路2:层序遍历

用队列实现。每遍历一层,则计数器 +1 ,直到遍历完成,则可得到树的深度。

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
        int res = 0;
        while(!queue.isEmpty()) {
        	for(int i = queue.size(); i >0 ; i--) {
        		TreeNode current = queue.poll();
        		if (current.left != null) queue.add(current.left);
        		if (current.right != null) queue.add(current.right);
        	}
            res++;
        }
        return res;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章