剑指 Offer 55 - I. 二叉树的深度——二叉树的遍历

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

题目描述

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

例如:

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

解题思路

每遍历一层,则计数器 +1 ,直到遍历完成,则可得到树的深度

递归方式进行遍历

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

非递归方式的层序遍历

树的层序遍历(广度优先遍历)往往利用队列实现

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

猜你喜欢

转载自blog.csdn.net/qq_35655602/article/details/114240047
今日推荐