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解法.

/**
 * 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;
        }

        Stack<TreeNode> stack = new Stack<>();
        Stack<Integer> depths = new Stack<>();
        stack.push(root);
        depths.push(1);
        int max = 1;
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            int depth = depths.pop();
            max = Math.max(max, depth);
            if (node.left != null) {
                stack.push(node.left);
                depths.push(depth + 1);
            }
            if (node.right != null) {
                stack.push(node.right);
                depths.push(depth + 1);
            }
        }
        return max;
    }
}

Last updated