【树】剑指 Offer 55 - I. 二叉树的深度

题目:

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

例如:

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

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

 

 

解答:

方法一:(DFS)

时间复杂度:O(n)

空间复杂度:O(n)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;

        if(root.left == null && root.right == null) return 1;

        return 1+ Math.max(maxDepth(root.left),maxDepth(root.right));
    }
}

方法二:(BFS)层序遍历

时间复杂度:O(n)

空间复杂度:O(n)

 

使用两个列表,queue,tmp 分别表示当前层和下一层。这样就可以达到一层一层遍历的效果。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
    
       if(root == null) return 0;
        
       List<TreeNode> queue = new LinkedList<>(),tmp;
       queue.add(root);
      
       int res = 0;
       while(!queue.isEmpty()){
        tmp = new LinkedList<>();
        for(TreeNode node : queue){
           if(node.left!=null) tmp.add(node.left);
           if(node.right!=null) tmp.add(node.right);
        }
        queue = tmp;
        res++;

       }
       return res;
    }
}

 

posted @ 2020-08-19 18:27  3KBLACK  阅读(43)  评论(0)    收藏  举报