Leetcode 刷题必须Review 十八 Lintcode(771 66 495 263 67 68)

文章目录

  • 771 · 二阶阶乘
  • 495 · 实现栈
  • 263 · 小括号匹配
  • 66 · 二叉树的前序遍历
  • 67 · 二叉树的中序遍历
  • 68 · 二叉树的后序遍历

771 · 二阶阶乘

给定一个数n,返回该数的二阶阶乘。在数学中,正整数的二阶阶乘表示不超过这个正整数且与它有相同奇偶性的所有正整数乘积。
Leetcode 刷题必须Review 十八 Lintcode(771 66 495 263 67 68)_第1张图片

def doubleFactorial(self, n):
        # Write your code here
        res = 1
        if n % 2 != 0:
            for i in range(n, 0, -2):
                res *= i
        else:
            for i in range(n, 1, -2):
                res *= i
        return res

官方答案,尾递归:

def doubleFactorial(self, n, result=1):
        if n <= 2:
            return n * result
        return self.doubleFactorial(n - 2, result * n)

495 · 实现栈

实现一个栈,可以使用除了栈之外的数据结构
Leetcode 刷题必须Review 十八 Lintcode(771 66 495 263 67 68)_第2张图片

class Stack:

    def __init__(self):
        self.stack = []

    """
    @param: x: An integer
    @return: nothing
    """
    def push(self, x):
        # write your code here
        self.stack.append(x)

    """
    @return: nothing
    """
    def pop(self):
        # write your code here
        self.stack.pop()

    """
    @return: An integer
    """
    def top(self):
        # write your code here
        return self.stack[-1]

    """
    @return: True if the stack is empty
    """
    def isEmpty(self):
        # write your code here
        return False if self.stack else True

263 · 小括号匹配

给定一个字符串所表示的括号序列,包含以下字符: ‘(’, ‘)’, 判定是否是有效的括号序列。

括号必须依照 “()” 顺序表示, “()” 是有效的括号,但 “)(” 则是无效的括号。

Leetcode 刷题必须Review 十八 Lintcode(771 66 495 263 67 68)_第3张图片

def match_parentheses(self, string: str) -> bool:
        # write your code here
        stack = []
        for ch in string:
            if ch == '(':
                stack.append(ch)
            elif ch == ")":
                if not stack: return False
                stack.pop()
        return len(stack) == 0

66 · 二叉树的前序遍历

给出一棵二叉树,返回其节点值的前序遍历。
Leetcode 刷题必须Review 十八 Lintcode(771 66 495 263 67 68)_第4张图片

from typing import (
    List,
)
from lintcode import (
    TreeNode,
)

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: A Tree
    @return: Preorder in ArrayList which contains node values.
    """
    def preorder_traversal(self, root: TreeNode) -> List[int]:
        # write your code here
        res = []
        self.dfs(root, res)
        return res

    def dfs(self, root, res):
        if not root: return
        res.append(root.val)
        if root.left:
            self.dfs(root.left, res)
        if root.right:
            self.dfs(root.right, res)
    

下面是不用递归的方法,用了stack,仿照了bfs的写法,主要right在先,left在后。

def preorder_traversal(self, root: TreeNode) -> List[int]:
        # write your code here
        if root is None:
            return []
        stack = [root]
        result = []
        while stack:
            node = stack.pop()
            result.append(node.val)
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
        return result

67 · 二叉树的中序遍历

给出一棵二叉树,返回其中序遍历。
Leetcode 刷题必须Review 十八 Lintcode(771 66 495 263 67 68)_第5张图片
写了一个不对。。。蒙圈了,没用递归。。。

from typing import (
    List,
)
from lintcode import (
    TreeNode,
)

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: A Tree
    @return: Inorder in ArrayList which contains node values.
    """
    def inorder_traversal(self, root: TreeNode) -> List[int]:
        # write your code here
        res = []
        self.dfs(root, res)
        return res
        
    def dfs(self, root, res):
        if not root: return
        if root.left:
            res.append(root.left.val)
        res.append(root.val)
        if root.right:
            res.append(root.right.val)
        

修改:

from typing import (
    List,
)
from lintcode import (
    TreeNode,
)

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: A Tree
    @return: Inorder in ArrayList which contains node values.
    """
    def inorder_traversal(self, root: TreeNode) -> List[int]:
        # write your code here
        res = []
        self.dfs(root, res)
        return res
        
    def dfs(self, root, res):
        if not root: return
        if root.left:
            self.dfs(root.left, res)
        res.append(root.val)
        if root.right:
            self.dfs(root.right, res)
        

看了一个非递归的方法:

def inorderTraversal(self, root):
        if root == None:
            return []
    
        stack = []
        output = []
        node = root
        while node or stack:
            while node:
                stack.append(node)
                node = node.left
                
            node = stack.pop()
            output.append(node.val)
            
            node = node.right
        return output

68 · 二叉树的后序遍历

给出一棵二叉树,返回其节点值的后序遍历。

from typing import (
    List,
)
from lintcode import (
    TreeNode,
)

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: A Tree
    @return: Postorder in ArrayList which contains node values.
    """
    def postorder_traversal(self, root: TreeNode) -> List[int]:
        # write your code here
        res = []
        self.dfs(root, res)
        return res

    def dfs(self, root, res):
        if not root: return 
        if root.left:
            self.dfs(root.left, res)
        if root.right:
            self.dfs(root.right, res)
        res.append(root.val)

你可能感兴趣的:(Leetcode刷题复习,leetcode,算法,职场和发展)