Skip to content

Instantly share code, notes, and snippets.

@yokolet
Created September 15, 2018 02:23
Show Gist options
  • Select an option

  • Save yokolet/b0c2b27df168aaa93ba9c6bde58467cb to your computer and use it in GitHub Desktop.

Select an option

Save yokolet/b0c2b27df168aaa93ba9c6bde58467cb to your computer and use it in GitHub Desktop.
Diameter of Binary Tree
"""
Description:
Given a binary tree, you need to compute the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two
nodes in a tree. This path may or may not pass through the root.
The length of path between two nodes is represented by the number of edges between them.
Example:
Input:
1
/ \
2 3
/ \
4 5
Output: 3 -- [4, 2, 1, 3] or [5, 2, 1, 3]
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def diameterOfBinaryTree(root):
"""
:type root: TreeNode
:rtype: int
"""
def walk(root):
if not root:
return 0, 0
else:
l_depth, l_diam = walk(root.left)
r_depth, r_diam = walk(root.right)
depth = max(l_depth, r_depth) + 1
diam = max(l_depth + r_depth, l_diam, r_diam)
return depth, diam
_, diameter = walk(root)
return diameter
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment