Maximum Depth of Binary Tree

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

Easy 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.

Thoughts

简单但很好体现了分治基本思想的一道题。先左后右再合并。树的最高深度是子树中最高深度 + 1。

Code

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }

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

Analysis

因为相当于把数遍历了遍,所以时间复杂度为O(n), n为结点数。

Ver. 2

Iterative + meta stack解法.

Last updated

Was this helpful?