天天看點

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

http://oj.leetcode.com/problems/maximum-depth-of-binary-tree/

Solution:

Pretty fundamental, recursively get the max depth of the binary tree

https://github.com/starcroce/leetcode/blob/master/maximum_depth_of_binary_tree.cpp 

// 48 ms for 38 test cases
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root == NULL){
            return 0;
        }
        int left_depth = maxDepth(root->left);
        int right_depth = maxDepth(root->right);
        return max(left_depth, right_depth) + 1;
    }
};