Leetcode-104. maximum-depth-of-binary-tree

目录

一 题目描述

二 题目求解


一 题目描述

求给定二叉树的最大深度,

最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量。

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

二 题目求解

2.1 递归解法

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        int lDepth = maxDepth(root.left);
        int rDepth = maxDepth(root.right);
        return 1+(lDepth>rDepth?lDepth:rDepth);
    }
}

2.2 使用 queue 进行层序遍历

public int maxDepth(TreeNode root) {
    if (root == null)
        return 0;
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    int res = 0;
    queue.add(root);
    while (!queue.isEmpty()) {
        int size = queue.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);
        }
        res++;
    }

    return res;
}
发布了67 篇原创文章 · 获赞 64 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/jack1liu/article/details/102510733
今日推荐