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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 helper(TreeNode* node, int depth){ | |
if(node==NULL) | |
return depth; | |
int d0=depth; | |
int d1=depth; | |
if(node->left!=NULL) | |
d0=helper(node->left, depth+1); | |
if(node->right!=NULL) | |
d1=helper(node->right, depth+1); | |
return max(d0, d1); | |
} | |
int maxDepth(TreeNode* root) { | |
if(root==NULL) | |
return 0; | |
return helper(root, 1); | |
} | |
}; |
Round2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
void DFS(TreeNode* root, int& maxDepth, int curDepth){ | |
if(root==NULL) | |
return; | |
maxDepth=max(maxDepth, curDepth); | |
DFS(root->left, maxDepth, curDepth+1); | |
DFS(root->right, maxDepth, curDepth+1); | |
} | |
int maxDepth(TreeNode* root) { | |
int depth=0; | |
if(root==NULL) | |
return depth; | |
DFS(root, depth, 1); | |
return depth; | |
} | |
}; |
No comments:
Post a Comment