Monday, March 7, 2016

LeetCode Q104: 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.


/**
* 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:
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;
}
};
view raw Q104.cpp hosted with ❤ by GitHub

No comments:

Post a Comment