-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdepth_of_binary_tree.py
More file actions
28 lines (25 loc) · 882 Bytes
/
depth_of_binary_tree.py
File metadata and controls
28 lines (25 loc) · 882 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Problem: Depth of Binary Tree
# (https://leetcode.com/problems/diameter-of-binary-tree/#/description)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
diameter = 0
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None: return 0
self.findDepth(root)
return self.diameter
def findDepth(self, root):
if root == None:
return 0
leftDepth = self.findDepth(root.left) + (0 if root.left == None else 1)
rightDepth = self.findDepth(root.right) + (0 if root.right == None else 1)
self.diameter = max(self.diameter, leftDepth + rightDepth)
return max(leftDepth, rightDepth)