LeetCode题解:Maximum Depth of Binary Tree

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.

思路:

树其实是图的一种特例。

在对树进行搜索的时候保留树深的信息。一旦遇到深度比已知最大深度大时,就更新已知最大树深。

题解:

/**
 * 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 max_depth;
    
    void traverse_depth(TreeNode* node, int depth)
    {
        if (node == nullptr)
        {
            if (depth > max_depth)
                max_depth = depth;
            return;
        }
        
        traverse_depth(node->left, depth + 1);
        traverse_depth(node->right, depth + 1);
    }
    
    int maxDepth(TreeNode *root) {
        max_depth = 0;
        
        traverse_depth(root, 0);
        return max_depth;
    }
};


你可能感兴趣的:(LeetCode)