題目: 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 farthe ...
題目:
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.
求二叉樹的深度,遞歸一下就可以求到了。
python新手(我)發現python中沒有三元運算符,不過可以用true_part if condition else false_part模擬。雖然我後面用max函數代替了三元運算符,也實現了功能。
1 class Solution(object): 2 def maxDepth(self, root): 3 if (root == None): 4 return 0 5 left_depth = self.maxDepth(root.left) 6 right_depth = self.maxDepth(root.right) 7 return max(left_depth, right_depth) + 1