LeetCode—104. Maximum Depth of Binary Tree


递归遍历即可

//url:https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
/**
 * 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:
    
    void maxDepth(TreeNode* root,int& depth,int level){
        if(!root)
            return ;
        level++;
        depth=depth>level?depth:level;
        if(root->left)
            maxDepth(root->left,depth,level);
        if(root->right)
            maxDepth(root->right,depth,level);
    }
    
    int maxDepth(TreeNode* root) {
        int depth=0;
        maxDepth(root,depth,0);
        return depth;
    }
};

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注