leetcode笔记: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.

二. 题目分析

这道题和Minimum Depth of Binary Tree一题相似,这个是求最大深度的,就是对二叉树进行递归,然后将子树的最大深度进行返回,最终得到这个树的最大深度。

这个方法的时间复杂度为:O(n),空间复杂度为:O(logn)。

三. 示例代码

// 时间复杂度为O(n),,空间复杂度O(logn)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;} };

四. 小结

无。

功夫不负有心人。

leetcode笔记:Maximum Depth of Binary Tree

相关文章:

你感兴趣的文章:

标签云: