示例#1
0
   \   \
   3    3
Note:
Bonus points if you could solve it both recursively and iteratively.
'''


from structs.binary_tree import generate_tree

class Solution(object):
    def isSymmetric(self, root):
        def is_symmetric(left_tree, right_tree):
            if left_tree is None and right_tree is None: return True
            elif left_tree is None or right_tree is None: return False
            else: return left_tree.val == right_tree.val and is_symmetric(left_tree.left, right_tree.right) and is_symmetric(left_tree.right, right_tree.left)
        if root is None: return True
        return is_symmetric(root.left, root.right)

if __name__ == '__main__':
    tree = generate_tree([1,2,2,3,4,4,3])
    print Solution().isSymmetric(tree)
    tree = generate_tree([1,2,2,None,3,None,3])
    print Solution().isSymmetric(tree)
    tree = generate_tree([1])
    print Solution().isSymmetric(tree)
    tree = None
    print Solution().isSymmetric(tree)
    tree = generate_tree([1,2])
    print Solution().isSymmetric(tree)

示例#2
0
 def test1(self):
     tree = generate_tree([3,1,4,None,2])
     for k in xrange(1, 5): self.assertEqual(Solution().kthSmallest(tree, k), k)
示例#3
0
 def test1(self):
     tree = generate_tree([2, 1, 4, None, None, 3])
     it, v = BSTIterator(tree), []
     while it.hasNext():
         v.append(it.next())
     self.assertEqual(v, [1, 2, 3, 4])
示例#4
0
from structs.binary_tree import generate_tree

class Solution(object):
    def levelOrderBottom(self, root):
        res = []
        if root is None: return res
        level = [root]
        while len(level) > 0:
            nx_level = []
            a = []
            for node in level:
                a.append(node.val)
                if node.left: nx_level.append(node.left)
                if node.right: nx_level.append(node.right)
            res.append(a)
            level = nx_level
        res.reverse()
        return res

if __name__ == '__main__':
    tree = generate_tree([3, 9, 20, None, None, 15, 7])
    print Solution().levelOrder(tree)
    tree = generate_tree([1,2,None,3])
    print Solution().levelOrder(tree)
    tree = generate_tree([1])
    print Solution().levelOrder(tree)
    tree = None
    print Solution().levelOrder(tree)

Return the sum = 12 + 13 = 25.
'''


from structs.binary_tree import generate_tree

class Solution(object):
    def sumNumbers(self, root):
        def walk(root, val):
            val = val * 10 + root.val
            if root.left is None and root.right is None: return val
            res = 0
            if root.left: res += walk(root.left, val)
            if root.right: res += walk(root.right, val)
            return res
        if root is None: return 0
        else: return walk(root, 0)

if __name__ == '__main__':
    tree = generate_tree([1,2,3])
    print Solution().sumNumbers(tree)
    tree = generate_tree([1])
    print Solution().sumNumbers(tree)
    tree = generate_tree([1,2])
    print Solution().sumNumbers(tree)
    tree = None
    print Solution().sumNumbers(tree)
    tree = generate_tree([1,2,3,4])
    print Solution().sumNumbers(tree)

示例#6
0
    def work(self, root, s):
        if root is None: return
        if root.left is None and root.right is None:
            if s == root.val:
                self.current_result.append(root.val)
                self.result.append(self.current_result[:])
                self.current_result.pop()
            return
        self.current_result.append(root.val)
        if root.left: self.work(root.left, s - root.val)
        if root.right: self.work(root.right, s - root.val)
        self.current_result.pop()

    def pathSum(self, root, s):
        self.result = []
        self.current_result = []
        self.work(root, s)
        return self.result


if __name__ == '__main__':
    tree = generate_tree(
        [5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, None, 5, 1])
    print Solution().pathSum(tree, 22)
    print Solution().pathSum(tree, 21)
    tree = None
    print Solution().pathSum(tree, 0)
    tree = generate_tree([1, 2])
    print Solution().pathSum(tree, 0)
    print Solution().pathSum(tree, 3)
示例#7
0
'''
Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
'''

from structs.binary_tree import generate_tree


class Solution(object):
    def isSameTree(self, p, q):
        if p is None and q is None: return True
        elif p is None or q is None: return False
        else:
            return p.val == q.val and self.isSameTree(
                p.left, q.left) and self.isSameTree(p.right, q.right)


if __name__ == '__main__':
    t1 = generate_tree([1, 2, 3])
    t2 = generate_tree([1, 2, None, None, 3])
    print Solution().isSameTree(t1, t2)
   / \
  2   3
Binary tree [1,2,3], return false.
'''


from structs.binary_tree import generate_tree

class Solution(object):
    def isValidBST(self, root):
        def is_valid(root, left, right):
            if root is None: return True
            val_check = (left is None or root.val > left) and (right is None or root.val < right)
            return val_check and is_valid(root.left, left, root.val) and is_valid(root.right, root.val, right)
        return is_valid(root, None, None)

if __name__ == '__main__':
    tree = generate_tree([2,1,3])
    print Solution().isValidBST(tree)
    tree = generate_tree([1,2,3])
    print Solution().isValidBST(tree)
    tree = generate_tree([1])
    print Solution().isValidBST(tree)
    tree = None
    print Solution().isValidBST(tree)
    tree = generate_tree([2,1,4,None,None,1,5])
    print Solution().isValidBST(tree)
    tree = generate_tree([0x7fffffff])
    print Solution().isValidBST(tree)

Note: Recursive solution is trivial, could you do it iteratively?
'''


from structs.binary_tree import generate_tree

class Solution(object):
    def inorderTraversal(self, root):
        stack = []
        res = []
        while True:
            while root:
                stack.append(root)
                root = root.left
            if len(stack) == 0: break
            root = stack.pop()
            res.append(root.val)
            root = root.right
        return res

if __name__ == '__main__':
    tree = generate_tree([1, None, 2, None, None, 3])
    print Solution().inorderTraversal(tree)
    tree = generate_tree([1, 2, None, 3, 5, None, None, 4])
    print Solution().inorderTraversal(tree)
    tree = generate_tree([1])
    print Solution().inorderTraversal(tree)
    tree = None
    print Solution().inorderTraversal(tree)

 def test1(self):
     import random
     for _ in xrange(100):
         n = random.randint(2, 10000)
         tree = generate_tree(range(n))
         self.assertEqual(Solution().countNodes(tree), n)
 def test2(self):
     tree = generate_tree([1])
     self.assertEqual(Solution().countNodes(tree), 1)
示例#12
0
from structs.binary_tree import generate_tree


# This solution is based on 144_Binary_Tree_Preorder_Traversal solution 1; a solution based on its solution 2 should also work.
class Solution(object):
    def postorderTraversal(self, root):
        ans = []
        if root is None: return ans
        stack = [(root, False)]
        while len(stack) > 0:
            node, flag = stack.pop()
            if flag or (node.left is None and node.right is None):
                ans.append(node.val)
            else:
                stack.append((node, True))
                if node.right: stack.append((node.right, False))
                if node.left: stack.append((node.left, False))
        return ans


if __name__ == '__main__':
    tree = generate_tree([1, None, 2, None, None, 3])
    print Solution().postorderTraversal(tree)
    tree = generate_tree([1, 2, 3, 4, 5, 6, 7])
    print Solution().postorderTraversal(tree)
    tree = generate_tree([1])
    print Solution().postorderTraversal(tree)
    tree = generate_tree([])
    print Solution().postorderTraversal(tree)
示例#13
0
 def test3(self):
     tree = generate_tree([1])
     self.assertEqual(Solution().rightSideView(tree), [1])
示例#14
0
 def test2(self):
     tree = generate_tree([1, 2, None, 3, None, None, None, 4, 5])
     self.assertEqual(Solution().rightSideView(tree), [1, 2, 3, 5])
示例#15
0
                    _, tail = walk(tail.right)
                    return root, tail
                else:
                    return root, tail
            elif root.right:
                _, tail = walk(root.right)
                return root, tail
            else:
                return root, root

        if root is None: return None
        walk(root)


if __name__ == '__main__':
    tree = generate_tree([1, 2, 5, 3, 4, None, 6])
    Solution().flatten(tree)
    print tree
    tree = generate_tree([1, 2, 3, 4])
    Solution().flatten(tree)
    print tree
    tree = generate_tree([1, 2, None, 3, None, None, None, 4])
    Solution().flatten(tree)
    print tree
    tree = generate_tree([1])
    Solution().flatten(tree)
    print tree
    tree = generate_tree([])
    Solution().flatten(tree)
    print tree
示例#16
0
                       root.val), max(left[1], right[1], 0) + root.val

        def max_node(root):
            m = root.val
            if root.left: m = max(m, max_node(root.left))
            if root.right: m = max(m, max_node(root.right))
            return m

        if root is None: return 0
        ans = work(root)[0]
        if ans == 0: ans = max_node(root)
        return ans


if __name__ == '__main__':
    tree = generate_tree([1, 2, 3])
    print Solution().maxPathSum(tree)
    tree = generate_tree([1, -2, 3])
    print Solution().maxPathSum(tree)
    tree = generate_tree([1, -2, -3])
    print Solution().maxPathSum(tree)
    tree = generate_tree([-1, -2, -3])
    print Solution().maxPathSum(tree)
    tree = generate_tree([-1, 2, -3])
    print Solution().maxPathSum(tree)
    tree = generate_tree([-1, 1, 4, 2, 3, 5, -1])
    print Solution().maxPathSum(tree)
    tree = generate_tree([-10, 1, 4, 2, 3, 5, -1])
    print Solution().maxPathSum(tree)
    tree = generate_tree([-1, 1, 4, 2, 3, -5, -1])
    print Solution().maxPathSum(tree)