|
| 1 | +# The diameter of a tree (sometimes called the width) |
| 2 | +# is the number of nodes on the longest path between |
| 3 | +# two end nodes. |
| 4 | + |
| 5 | +# The diameter of a tree T is the largest of the following quantities: |
| 6 | + |
| 7 | +# * the diameter of T’s left subtree |
| 8 | +# * the diameter of T’s right subtree |
| 9 | +# * the longest path between leaves that goes through the |
| 10 | +# root of T (this can be computed from the heights of the subtrees of T) |
| 11 | + |
| 12 | +class Node(object): |
| 13 | + def __init__(self, data): |
| 14 | + self.data = data |
| 15 | + self.left = None |
| 16 | + self.right = None |
| 17 | + |
| 18 | +def height(tree): |
| 19 | + if tree is None: |
| 20 | + return 0 |
| 21 | + else: |
| 22 | + return 1 + max(height(tree.left), height(tree.right)) |
| 23 | + |
| 24 | +def diameter(tree): |
| 25 | + if tree is None: |
| 26 | + return 0 |
| 27 | + |
| 28 | + else: |
| 29 | + lheight = height(tree.left) |
| 30 | + rheight = height(tree.right) |
| 31 | + |
| 32 | + ldiameter = diameter(tree.left) |
| 33 | + rdiameter = diameter(tree.right) |
| 34 | + |
| 35 | + return max(rheight + lheight + 1, max(ldiameter, rdiameter)) |
| 36 | + |
| 37 | +root = Node(1) |
| 38 | +root.left = Node(2) |
| 39 | +root.right = Node(3) |
| 40 | +root.left.left = Node(4) |
| 41 | +root.left.right = Node(5) |
| 42 | +print("Diameter of given binary tree is ",diameter(root)) |
0 commit comments