Przeglądaj źródła

April Day 11 done

master
Lachlan Jacob 5 lat temu
rodzic
commit
dc062a0274
3 zmienionych plików z 46 dodań i 0 usunięć
  1. 29
    0
      problems/543/main.py
  2. 14
    0
      problems/543/problem.txt
  3. 3
    0
      problems/543/run.sh

+ 29
- 0
problems/543/main.py Wyświetl plik

@@ -0,0 +1,29 @@
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None

class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
if root is not None:
l = self.height(root.left)
r = self.height(root.right)
ldiameter = self.diameterOfBinaryTree(root.left)
rdiameter = self.diameterOfBinaryTree(root.right)
return max(l + r, max(ldiameter, rdiameter))
return 0
def height(self, tree):
if tree is None:
return 0
return 1 + max(self.height(tree.left), self.height(tree.right))

s = Solution()
print("Expected: 3")
bt = TreeNode(1)
bt.left = TreeNode(2)
bt.right = TreeNode(3)
bt.left.left = TreeNode(4)
bt.left.right = TreeNode(5)
print("Got:", s.diameterOfBinaryTree(bt))

+ 14
- 0
problems/543/problem.txt Wyświetl plik

@@ -0,0 +1,14 @@
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.

Example:
Given a binary tree

1
/ \
2 3
/ \
4 5

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

+ 3
- 0
problems/543/run.sh Wyświetl plik

@@ -0,0 +1,3 @@
#!/bin/bash

python3 main.py

Ładowanie…
Anuluj
Zapisz