leetcode刷题之二叉树

二叉树(前序,中序,后序,层序)遍历递归与循环的python实现(五颗星)

113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5
/
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:
[
[5,4,11,2],
[5,8,4,5]
]

  • 思路:利用递归的思想解决
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def pathSum(self, root, sum):
        """
        :type root: TreeNode
        :type sum: int
        :rtype: List[List[int]]
        """
        import copy
        def find_sum_tree(root, he, sum, item, result):
            if root == None:
                return 
            item.append(root.val)
            he += root.val
            if he == sum and not root.left and  not root.right:
                item_deep = copy.deepcopy(item)
                result.append(item_deep)
            find_sum_tree(root.left, he, sum, item, result)
            find_sum_tree(root.right, he, sum, item, result)
            he -= item[-1]
            item.pop()
            
        he = 0
        item = []
        result = []
        find_sum_tree(root, he, sum, item, result)
        return result
               

题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

  • python 解答
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回构造的TreeNode根节点
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if not pre or not tin:
            return None
        node = TreeNode(pre.pop(0))
        index = tin.index(node.val)
        node.left = self.reConstructBinaryTree(pre, tin[ :index])
        node.right = self.reConstructBinaryTree(pre, tin[index+1: ])
        return node

98. 验证二叉搜索树

给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/
1 3
输出: true
示例 2:
输入:
5
/
1 4
/
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。

  • python 解答一:
    二叉搜索树的中序遍历一定是一个递增的序列,先得到中序遍历的list,之后再进行判断是否是递增的。
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        def inorder(root):
            if root == None:
                return []
            return inorder(root.left) + [root.val] + inorder(root.right)
        
        inorder_list = inorder(root)
        if inorder_list == sorted(list(set(inorder_list))):
            return True
        return False
  • 思路二:
    利用递归的思想,判断是否所有的节点是否都是满足条件。
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        '''
        def inorder(root):
            if root == None:
                return []
            return inorder(root.left) + [root.val] + inorder(root.right)
        
        inorder_list = inorder(root)
        if inorder_list == sorted(list(set(inorder_list))):
            return True
        return False
        '''

        return self.helper(root)
    
    
    def helper(self, root, left=None, right=None):
        if not root:
            return True
        if left and left.val >= root.val:
            return False
        if right and right.val <= root.val:
            return False
        return self.helper(root.left, left, root) and\
               self.helper(root.right, root, right)

589. N叉树的前序遍历

给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3叉树 :
在这里插入图片描述返回其前序遍历: [1,3,5,6,2,4]。

  • python 解答
    递归方法
"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        results = []
        self.function(root, results)
        return results
    
    
    def function(self, root, results):
        if root is None:
            return

        results.append(root.val)
        for child in root.children:
            if child is not None:
                self.function(child, results)
        
        

猜你喜欢

转载自blog.csdn.net/m0_37327467/article/details/88181621
今日推荐