示例#1
0
from leetcode.common import TreeNode


def binaryTreePaths(root):
    """
    :type root: TreeNode
    :rtype: List[str]
    """
    ret = []

    def handle(node, path):
        path += "->%s" % node.val
        if node.left:
            handle(node.left, path)
        if node.right:
            handle(node.right, path)
        if node.right is None and node.left is None:
            ret.append(path)

    if root is not None:
        if root.left:
            handle(root.left, "%s" % root.val)
        if root.right:
            handle(root.right, "%s" % root.val)
        if root.right is None and root.left is None:
            ret.append(str(root.val))
    return ret


print binaryTreePaths(TreeNode.stringToTreeNode("[1,2,3,4,5]"))
from leetcode.common import TreeNode


def lowestCommonAncestor(root, p, q):
    """
    :type root: TreeNode
    :type p: TreeNode
    :type q: TreeNode
    :rtype: TreeNode
    """
    stock = [root]
    lt = min(p.val, q.val)
    lg = max(p.val, q.val)
    while stock:
        tmp = []
        for node in stock:
            if lt <= node.val <= lg:
                return node
            if node.left:
                tmp.append(node.left)
            if node.right:
                tmp.append(node.right)
        stock = tmp


root = TreeNode.stringToTreeNode("[2,1]")
p = TreeNode.stringToTreeNode("[2]")
q = TreeNode.stringToTreeNode("[1]")
print lowestCommonAncestor(root, p, q)