LeetCode_Maximum Depth of Binary Tree

一.題目

Maximum Depth of Binary Tree

  Total Accepted: 70693 Total Submissions: 156776My Submissions

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.

Show Tags
Have you met this question in a real interview?  
Yes
 
No

Discuss





二.解題技巧

    這道題和Minimum Depth of Binary Tree類似,只不過這個是求最大深度的,解法也和Minimum Depth of Binary Tree一樣,都是對二叉樹進行遞歸,然後將子樹的最大深度進行返回,最終得到這個樹的最大深度。
    這個方法的時間複雜度爲O(n),空間複雜都爲O(logn)。


三.實現代碼

#include <iostream>

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/


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)
        {
            return 0;
        }

        int Result = 1;
        int Left = maxDepth(root->left);
        int Right = maxDepth(root->right);

        if (Left * Right)
        {
            Result += Left < Right? Right : Left;
        }
        else
        {
            Result += Right + Left;
        }

        return Result;
    }
};




四.體會

    這是一道類似的題,只是改改代碼就可以實現了。



版權所有,歡迎轉載,轉載請註明出處,謝謝微笑





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章