2021-08-19

Code 1

Question

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2

Input: head = [1,2]
Output: [2,1]

Example 3

Input: head = []
Output: []

Solution

  • 迭代
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        prev=None

        while head :
            next=head.next
            head.next=prev
            prev=head
            head=next
        return prev

在遍历链表时,将当前节点的 next \textit{next} next 指针改为指向前一个节点。由于节点没有引用其前一个节点,因此必须事先存储其前一个节点。在更改引用之前,还需要存储后一个节点。最后返回新的头引用。

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next :
            return head
        
        p=self.reverseList(head.next)
        
        head.next.next=head
        head.next=None
        
        return p

注意几点 :

  1. 相当于从最后一个向前换
  2. 交换部分代码head.next.next=head head.next=None
  3. p一直是最后一个节点

Code 2

Question

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).Implement the MyQueue class.

void push(int x) Pushes element x to the back of the queue.
int pop() Removes the element from the front of the queue and returns it.
int peek() Returns the element at the front of the queue.
boolean empty() Returns true if the queue is empty, false otherwise.

Notes
You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack’s standard operations.

Example 1

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]

Explanation

MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

Answer

  • 使用两个栈
class MyQueue(object):
    def __init__(self):
        self.stack1=[]
        self.stack2=[]
        self.front=None

    def push(self, x):
        if not self.stack1 :
            self.front=x
        while self.stack1  :
            self.stack2.append(self.stack1.pop())
        self.stack2.append(x)
        while self.stack2 :
            self.stack1.append(self.stack2.pop())

    def pop(self):
        p=self.stack1.pop()
        if self.stack1 :
            self.front=self.stack1[-1]
        return p

    def peek(self):
        return self.front

    def empty(self):
        if self.stack1 :
            return False
        else :
            return True

stack2主要用于反转列表

Code 3

Question

Given the root of a binary tree, return the preorder traversal of its nodes’ values.

Example 1

Input: root = [1,null,2,3]
Output: [1,2,3]

Example 2

Input: root = []
Output: []

Example 3

Input: root = [1]
Output: [1]

Example 4

Input: root = [1,2]
Output: [1,2]

Example 5

Input: root = [1,null,2]
Output: [1,2]

Answer

  • 递归
class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        l=[]
        self.preorder(root,l)
        return l

    def preorder(self,root,l) :
        if not root :
            return
        l.append(root.val)
        self.preorder(root.left,l)
        self.preorder(root.right,l)
  • 迭代
class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root :
            return []
        stack=[]
        ans=[]
        stack.append(root)
        while stack :
            p=stack.pop()
            ans.append(p.val)
            if p.right :
                stack.append(p.right)
            if p.left :
                stack.append(p.left)
        return ans

利用栈来解决,因为前序遍历是中->左->右,所以入栈顺序是右->左->中。

Code 4

Question

Given the root of a binary tree, return the postorder traversal of its nodes’ values.

Example 1

Input: root = [1,null,2,3]
Output: [3,2,1]

Example 2

Input: root = []
Output: []

Example 3

Input: root = [1]
Output: [1]

Example 4

Input: root = [1,2]
Output: [2,1]

Example 5

Input: root = [1,null,2]
Output: [2,1]

Answer

  • 递归
class Solution(object):
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        l=[]
        self.postorder(root,l)
        return l

    def postorder(self,root,l):
        if not root :
            return 
        self.postorder(root.left,l)
        self.postorder(root.right,l)
        l.append(root.val)
  • 迭代
    注意这里没看懂!!

Code 5

Question

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Example 1

Input: root = [1,2,2,3,4,4,3]
Output: true

Example 2

Input: root = [1,2,2,null,3,null,3]
Output: false

Answer

  • 递归
    分解成小问题------树对称-------子树对称----子树的子树对称----直到两节点均为空
class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root :
            return True
        return self.symmetric(root.left,root.right)

    def symmetric(self,l,r):
        if not l and not r :
            return True

        if l and r and (l.val==r.val) :
            return self.symmetric(l.left,r.right) and self.symmetric(l.right,r.left)

        else :
            return False
  • 迭代法
class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root  or not (root.left or root.right):
            return True
        queue=[root.right,root.left]
       
        while queue :
            left=queue.pop()
            right=queue.pop()

            if not (left or right) :
                continue
            if not (left and right) :
                return False
            if left.val!=right.val :
                return False

            queue.append(left.left)
            queue.append(right.right)
            queue.append(left.right)
            queue.append(right.left)
        return True

思路基本相同,使用了队列。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值