Skip to content

Commit 3d52408

Browse files
committed
Solve: maxDepth
1 parent 63cb397 commit 3d52408

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def maxDepth(self, root: Optional[TreeNode]) -> int:
9+
count = 0
10+
stacks1 = [root]
11+
stacks2= []
12+
13+
if root is None:
14+
return count
15+
while len(stacks1) > 0 :
16+
count += 1
17+
while len(stacks1) > 0 :
18+
node = stacks1.pop()
19+
20+
if node.left is not None:
21+
stacks2.append(node.left)
22+
if node.right is not None:
23+
stacks2.append(node.right)
24+
stacks1.extend(stacks2)
25+
stacks2 = []
26+
return count
27+
28+
"""
29+
class Solution:
30+
def maxDepth(self, root: Optional[TreeNode]) -> int:
31+
def depth(node, dep):
32+
if (node.left is None) and (node.right is None):
33+
return dep
34+
if (node.left is not None) and (node.right is None):
35+
return depth(node.left, dep+1)
36+
if (node.left is None) and (node.right is not None):
37+
return depth(node.right, dep+1)
38+
else:
39+
return max(depth(node.left, dep+1), depth(node.right, dep+1))
40+
if root is None:
41+
return 0
42+
return depth(root, 1)
43+
"""

0 commit comments

Comments
 (0)