LeetCode104-二叉树的最大深度

 

非商业,LeetCode链接附上:

https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

进入正题。

 

题目:

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

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

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

 

示例:

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

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

 

代码实现:

//节点
class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
 
        public TreeNode(int val) {
            this.val = val;
        }
}

//方法一 递归
public int maxDepth(TreeNode root) {

        if(root == null) {
            return 0;
        }
        
        int leftHeight = maxDepth(root.left);
        int rightHeight = maxDepth(root.right);
        return Math.max(leftHeight, rightHeight) + 1;
}
//时间复杂度O(n)
//空间复杂度O(height),其中height 表示二叉树的高度。递归函数需要栈空间,而栈空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。

//方法二 广度优先搜索
public int maxDepth(TreeNode root) {

        if(root == null) {
            return 0;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int ans = 0;
        while(!queue.isEmpty()) {

            int size = queue.size();
            while(size > 0) {
                TreeNode node = queue.poll();
                if(node.left != null) {
                    queue.offer(node.left);
                }
                if(node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            ans++;
        }

        return ans;
}
//时间复杂度O(n),空间复杂度O(n)

  

分析:

树的相关算法大多可以用递归的方法解决。代码好写也比较好理解,要注意的点是确定好递归的结束条件。

广度优先搜索,不仅可以求深度(本题),还可以进行二叉树的层序遍历。非递归的方法也是需要掌握的。

 

--End

 

posted @ 2020-12-01 11:09  黑冰台  阅读(96)  评论(0)    收藏  举报