LeetCode - Maximum Depth of Binary Tree

来源:互联网 发布:c语言嵌入式开发 编辑:程序博客网 时间:2024/06/16 12:58

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

0 0