Maximum Depth of Binary Tree

// maxiumdepthoftreenode.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include "pch.h"
#include 
#include 
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};



class Solution {
public:
    int num;
    int maxDepth(TreeNode* root) {
        if (!root) return 0;
        num = numeric_limits::min();
        travel(root, 1);
        return num;
    }

    void travel(TreeNode* node, int level) {
        if (!node->left && !node->right) {
            num = max(level, num);
            return;
        }

        if (node->left) {
            travel(node->left, level + 1);
        }

        if (node->right) {
            travel(node->right, level + 1);
        }
    }

};
int main()
{
    TreeNode* root = new TreeNode(3);
    TreeNode* left9 = new TreeNode(9);
    TreeNode* right20 = new TreeNode(20);
    TreeNode* left15 = new TreeNode(15);
    TreeNode* right7 = new TreeNode(7);
    root->left = left9;
    root->right = right20;
    right20->left = left15;
    right20->right = right7;


    

    Solution s;
    int depth = s.maxDepth(root);
    cout << depth << endl;

    delete right7;
    delete left15;
    delete right20;
    delete left9;
    delete root;
    return 0;
}

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