Skip to content

Commit 6d76ec0

Browse files
committed
Create 104. Maximum Depth of Binary Tree.py
1 parent 75daf44 commit 6d76ec0

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

104. Maximum Depth of Binary Tree.py

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# -*- coding: utf-8 -*-
2+
# @Time : 2019/3/4 18:01
3+
# @Author : xulzee
4+
5+
# @File : 104. Maximum Depth of Binary Tree.py
6+
# @Software: PyCharm
7+
8+
# Definition for a binary tree node.
9+
class TreeNode:
10+
def __init__(self, x):
11+
self.val = x
12+
self.left = None
13+
self.right = None
14+
15+
class Solution:
16+
def maxDepth(self, root):
17+
"""
18+
:type root: TreeNode
19+
:rtype: int
20+
"""
21+
if root == None:
22+
return 0
23+
max_left = self.maxDepth(root.left)
24+
max_right = self.maxDepth(root.right)
25+
return max(max_left, max_right) + 1
26+
27+
28+
def stringToTreeNode(input):
29+
input = input.strip()
30+
input = input[1:-1]
31+
if not input:
32+
return None
33+
34+
inputValues = [s.strip() for s in input.split(',')]
35+
root = TreeNode(int(inputValues[0]))
36+
nodeQueue = [root]
37+
front = 0
38+
index = 1
39+
while index < len(inputValues):
40+
node = nodeQueue[front]
41+
front = front + 1
42+
43+
item = inputValues[index]
44+
index = index + 1
45+
if item != "null":
46+
leftNumber = int(item)
47+
node.left = TreeNode(leftNumber)
48+
nodeQueue.append(node.left)
49+
50+
if index >= len(inputValues):
51+
break
52+
53+
item = inputValues[index]
54+
index = index + 1
55+
if item != "null":
56+
rightNumber = int(item)
57+
node.right = TreeNode(rightNumber)
58+
nodeQueue.append(node.right)
59+
return root
60+
61+
62+
def main():
63+
import sys
64+
import io
65+
def readlines():
66+
for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
67+
yield line.strip('\n')
68+
69+
lines = readlines()
70+
while True:
71+
try:
72+
line = next(lines)
73+
root = stringToTreeNode(line);
74+
75+
ret = Solution().maxDepth(root)
76+
77+
out = str(ret);
78+
print(out)
79+
except StopIteration:
80+
break
81+
82+
83+
if __name__ == '__main__':
84+
main()

0 commit comments

Comments
 (0)