104. 二叉树的最大深度 (easy)

 

递归: 先序遍历

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

    int maxDepth(TreeNode* root) {
        int depth = 0;
        if (root != NULL) depth = 1;
        PreOrder(root, depth);
        return ans;
    }
};

 

posted on 2022-10-14 16:46  hannah_id  阅读(28)  评论(0)    收藏  举报

导航