LeetcodeツリーMaximm Depth of Binary Tree
940 ワード
この記事はsenlieオリジナルです。転載はこの住所を残してください。http://blog.csdn.net/zhengsenlie
Maximum Depth of Binary Tree
Total Acceepted: 16605
Total Submissions: 38287
Given a binary tree、find its maximum depth.
The maximm depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
与えられた一本の二叉の木の最大の深さを求めます。
考え方:dfs再帰。ツリーの最大深さ=max(左サブツリーの最大深さ、右サブツリーの最大深さ)+1
複雑度:時間O(n)(各ノードが一回訪問するため)、空間O(logn)(再帰的な圧力スタックはrootポインタを保存するため、スタックは最大lognとなる)
関連テーマ:Minimum Depth of Binary Tree
Maximum Depth of Binary Tree
Total Acceepted: 16605
Total Submissions: 38287
Given a binary tree、find its maximum depth.
The maximm depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
与えられた一本の二叉の木の最大の深さを求めます。
考え方:dfs再帰。ツリーの最大深さ=max(左サブツリーの最大深さ、右サブツリーの最大深さ)+1
複雑度:時間O(n)(各ノードが一回訪問するため)、空間O(logn)(再帰的な圧力スタックはrootポインタを保存するため、スタックは最大lognとなる)
関連テーマ:Minimum Depth of Binary Tree
/**
* Definition for binary tree
* 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 == NULL) return 0;
return max(maxDepth(root->left) , maxDepth(root->right)) + 1;
}
};