删除链表中重复的结点
题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
解题思路:
法一:链表里面所有的数存在一个列表里面,然后把列表里面只出现一次的数提取出来,再新建一个链表放进去
法二:只用一次遍历,两个指针,一个指向重复结点上一个结点,一个指向重复结点后一个值。前后比较是否相等。
代码:
法一:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
res = []
while pHead:
res.append(pHead.val)
pHead = pHead.next
#filter 与map相似,但是filter返回的是bool去除重复进行判断
res = list(filter(lambda c:res.count(c) == 1, res))
newlist = ListNode(0)
pre = newlist
for i in res:
node = ListNode(i)
pre.next = node
pre = pre.next
return newlist.next
法二:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
#检查空或只有一个元素
if pHead is None or pHead.next is None:
return pHead
#防止第一个就是重复结点,创造一个新的头节点。
first = ListNode(-1)
first.next = pHead
last = first
while pHead and pHead.next:
if pHead.val ==pHead.next.val:
val = pHead.val #保存值
while pHead and val==pHead.val:
pHead = pHead.next
last.next = pHead #最后一个指针指向个数
else:
last = pHead
pHead = pHead.next
return first.next
二叉树的下一个结点
题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
解题思路:
1.二叉树为空,则返回空;
2.节点右孩子存在,则设置一个指针从该节点的右孩子出发,一直沿着指向左子结点的指针找到的叶子节点即为下一个节点;
3.节点不是根节点。如果该节点是其父节点的左孩子,则返回父节点;否则继续向上遍历其父节点的父节点,重复之前的判断,返回结果。
首先知道中序遍历的规则是:左根右,然后作图
结合图,我们可发现分成两大类:1、有右子树的,那么下个结点就是右子树最左边的点;(eg:D,B,E,A,C,G) 2、没有右子树的,也可以分成两类,a)是父节点左孩子(eg:N,I,L) ,那么父节点就是下一个节点 ; b)是父节点的右孩子(eg:H,J,K,M)找他的父节点的父节点的父节点...直到当前结点是其父节点的左孩子位置。如果没有eg:M,那么他就是尾节点。
代码:
# -*- coding:utf-8 -*-
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
def GetNext(self, pNode):
# write code here
if not pNode:
return None
if pNode.right:#右存在,右子树的最左边
pNode = pNode.right
while pNode.left:
pNode = pNode.left
return pNode
else:
while pNode.next:#不是根结点
if pNode == pNode.next.left:#左子树上,下一节点是父节点
return pNode.next
pNode = pNode.next
return None
对称的二叉树
题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
解题思路:
递归来做。根不变,左右子树交换。
代码:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetrical(self, pRoot):
# write code here
return self.IsSymmetrical(pRoot,pRoot)
def IsSymmetrical(self, pRoot1,pRoot2):
if pRoot1 == None and pRoot2 == None:
return True
if pRoot1 == None or pRoot2 == None:
return False
if pRoot1.val != pRoot2.val:
return False
return self.IsSymmetrical(pRoot1.left, pRoot2.right) and self.IsSymmetrical(pRoot1.right,pRoot2.left)