二叉树相关编程题总结

1、二叉树后序遍历

class Solution(object):
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        res = []
        def helper(root):
            if not root:
                return
            helper(root.left)
            helper(root.right)
            res.append(root.val)
        helper(root)
        return res

2、从前序与中序遍历序列构造二叉树

class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        def helper(inc_start, inc_end):
            if inc_start == inc_end:
                return None
            inc_value = preorder[self.pre_index]
            root = TreeNode(inc_value)
            self.pre_index += 1
            root.left = helper(inc_start, inc_value_map[inc_value])
            root.right = helper(inc_value_map[inc_value] + 1, inc_end)
            return root
        self.pre_index = 0
        inc_value_map = {v: k for k, v in enumerate(inorder)}
        return helper(0, len(inorder))

3、从后序与中序遍历序列构造二叉树

class Solution(object):
    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        def helper(in_start, in_end):
            if in_start == in_end:
                return None
            val = postorder[self.pos_index]
            root = TreeNode(val)
            self.pos_index -= 1
            root.right = helper(inc_map[val] + 1, in_end) 
            root.left = helper(in_start, inc_map[val])
            return root
        self.pos_index = len(postorder) - 1
        inc_map = {v:k for k,v in enumerate(inorder)}
        return helper(0, len(postorder))
posted @ 2019-12-22 01:12  WESWES  阅读(360)  评论(0编辑  收藏  举报