LeetCode OJ-- Maximum Depth of Binary Tree

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

求二叉树的最大深度

深度优先搜索

/**
 * 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) {
        if(root == NULL)
            return 0;
        
        int ans = 0;
        int now_depth;
        deep(root,ans,1);
        return ans;
    }
    
    void deep(TreeNode *root, int &max_depth, int now_depth)
    {
        if(root->left == NULL && root->right == NULL)
            max_depth = max_depth < now_depth ? now_depth : max_depth;
            
        now_depth++;
        
        if(root->left)
            deep(root->left,max_depth,now_depth);
        if(root->right)
            deep(root->right,max_depth,now_depth);
    }
};
原文地址:https://www.cnblogs.com/qingcheng/p/3829497.html