Skip to content

Latest commit

 

History

History
64 lines (51 loc) · 1.26 KB

0104._Maximum_Depth_of_Binary_Tree.md

File metadata and controls

64 lines (51 loc) · 1.26 KB

104. Maximum Depth of Binary Tree

难度:Easy

刷题内容

原题连接

内容描述

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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
return its depth = 3.

思路 - 时间复杂度: O(N)- 空间复杂度: O(N)******

用DFS递归遍历二叉树,分别找到二叉树的左子树与右子树的 depth。比较左子树和右子树的 depth的大小。

/**
 * 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) {
        return max(root,0);
    }
    int max(TreeNode* ptr,int deep)
    {
        if(ptr != nullptr)
        {
            int ldeep = max(ptr ->left,deep + 1);
            int rdeep = max(ptr ->right,deep + 1);
            if(ldeep > rdeep) 
                deep = ldeep; 
            else
                deep = rdeep;
        }
        return deep;
    }
};