104. 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.

 

104. Максимальная глубина бинарного дерева

 

Задано бинарное дерево. Найдите его наибольшую глубину.

Максимальной глубиной дерева называется количество вершин на пути от корня до самого отдаленного листа.

 

// C++

/**

 * 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:

  int maxDepth(TreeNode* root) {

       

  }

};

 

// Java

/**

 * Definition for a binary tree node.

 * public class TreeNode {

 *     int val;

 *     TreeNode left;

 *     TreeNode right;

 *     TreeNode(int x) { val = x; }

 * }

 */

public class Solution {

  public int maxDepth(TreeNode root) {

       

  }

}

 

РЕШЕНИЕ

структуры данных - деревья

 

Анализ алгоритма

Если root = NULL, то глубина дерева равна 0.

Ищем глубину левого Left и  правого Right поддерева. Тогда глубина самого дерева равна

max(Left, Right) + 1

 

Реализация алгоритма

 

class Solution

{

public:

  int maxDepth(TreeNode* root)

  {

    if (root == NULL) return 0;

    int Left = maxDepth(root->left);

    int Right = maxDepth(root->right);

    return max(Left,Right) + 1;

  }

};

 

Java реализация

 

public class Solution

{

  public int maxDepth(TreeNode root)

  {

    if (root == null) return 0;

    int Left = maxDepth(root.left);

    int Right = maxDepth(root.right);

    return Math.max(Left,Right) + 1;

  }

}