Leetcode 104. Maximum Depth of Binary Tree

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Maximum Depth of Binary Tree

2. Solution

  • Version 1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        int maxDepth = 0;
        preorderTraverse(root, 0, maxDepth);
        return maxDepth;
    }
    
private:
    void preorderTraverse(TreeNode* root, int depth, int& maxDepth) {
        if(!root) {
            return;
        }
        depth++;
        if(depth > maxDepth) {
            maxDepth = depth;
        }
        preorderTraverse(root->left, depth, maxDepth);
        preorderTraverse(root->right, depth, maxDepth);
    }
};
  • Version 2
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root) {
            return 0;
        }
        return max(maxDepth(root->left), maxDepth(root->right)) + 1;
    }
};

Reference

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

你可能感兴趣的:(Leetcode 104. Maximum Depth of Binary Tree)