Skip to content

Commit 2323d4d

Browse files
committed
solve : maximum depth of binary tree
1 parent 94011da commit 2323d4d

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed
Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,53 @@
1-
//set-up
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
int maxDepth(TreeNode* root) {
15+
16+
//root가 비어있는 경우
17+
if(root == nullptr)
18+
{
19+
return 0;
20+
}
21+
22+
stack<TreeNode*> nodeStack;
23+
stack<int> depthStack;
24+
int maxDepth = 0;
25+
26+
nodeStack.push(root);
27+
depthStack.push(1);
28+
29+
while(!nodeStack.empty())
30+
{
31+
TreeNode* rootNode = nodeStack.top(); //change root pointer
32+
int rootDepth = depthStack.top();
33+
maxDepth = max(maxDepth, rootDepth);
34+
nodeStack.pop();
35+
depthStack.pop();
36+
37+
//making max depth binary tree
38+
if(rootNode->left != nullptr)
39+
{
40+
nodeStack.push(rootNode->left);
41+
depthStack.push(rootDepth+1);
42+
}
43+
44+
if(rootNode->right != nullptr)
45+
{
46+
nodeStack.push(rootNode->right);
47+
depthStack.push(rootDepth+1);
48+
}
49+
50+
}
51+
return maxDepth;
52+
}
53+
};

0 commit comments

Comments
 (0)