Exemplo n.º 1
0
            queue.append(root)
            while queue:
                node = queue.pop(0)
                levelNo = levels.pop(0)
                if lastLevel != levelNo:
                    result.append(tList)
                    tList = []
                    lastLevel = levelNo
                tList.append(node.val)
                if node.left:
                    queue.append(node.left)
                    levels.append(levelNo + 1)
                if node.right:
                    queue.append(node.right)
                    levels.append(levelNo + 1)
        result.append(tList)
        return result


# Testing
node1 = TreeNode(3)
node2 = TreeNode(2)
node3 = TreeNode(5)
node4 = TreeNode(1)
node1.left = node2
node1.right = node3
node2.left = node4

solution = Solution()
print(solution.levelOrder(node1))

#Testing
node1 = TreeNode(3)
node2 = TreeNode(5)
node3 = TreeNode(1)
node4 = TreeNode(6)
node5 = TreeNode(2)
node6 = TreeNode(7)
node7 = TreeNode(4)
node8 = TreeNode(0)
node9 = TreeNode(8)
node10 = TreeNode(10)
node11 = TreeNode(11)

node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node5.left = node6
node5.right = node7
node3.left = node8
node3.right = node9

solution = Solution()
lca = solution.lowestCommonAncestor(node1,node3,node8)
if lca is not None:
    print lca.val
else:
    print 'No LCS'
Exemplo n.º 3
0
from treeStructure import TreeNode
class Solution():
    def findDiameter(self, root):
        if not root:
            return 0
        else:
            lH,rH = self.treeHeight(root.left),self.treeHeight(root.right)
            return max(1+lH+rH,self.findDiameter(root.left),self.findDiameter(root.right))

    def treeHeight(self,root):
        if not root:
            return 0
        else:
            return 1 + max(self.treeHeight(root.left),self.treeHeight(root.right))

#Testing
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left  = TreeNode(4)
root.left.right = TreeNode(5)
print(Solution().findDiameter(root))