Created
August 20, 2017 07:25
-
-
Save farkwun/0727550f9f1d4fd1c0d2e8fbbcba4266 to your computer and use it in GitHub Desktop.
543. Diameter of Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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): | |
max_path = 0 | |
def diameterOfBinaryTree(self, root): | |
""" | |
:type root: TreeNode | |
:rtype: int | |
""" | |
self.max_path = 0 | |
self.ioTraverse(root, 0) | |
return self.max_path | |
def ioTraverse(self, node, level): | |
if not node: | |
return 0 | |
left_depth = self.ioTraverse(node.left, level + 1) | |
right_depth = self.ioTraverse(node.right, level + 1) | |
longest_path_through_myself = (left_depth - level) + (right_depth - level) | |
self.max_path = max(longest_path_through_myself, self.max_path) | |
return max(left_depth, right_depth, level) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment