删除链表中重复的结点
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
- 三个结点 注意边界条件
class Solution:
def deleteDuplication(self, pHead):
# write code here
head=ListNode(0)
head.next=pHead
slow=head
fast=head.next
while fast:
if fast.next and fast.val == fast.next.val:
while fast.next and fast.val == fast.next.val:
fast=fast.next
fast=fast.next
slow.next=fast
else:
fast=fast.next
slow=slow.next
return head.next
二叉树的下一个结点
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
三个关键
- 1.二叉树为空,则返回空;
- 2.节点右孩子存在,则设置一个指针从该节点的右孩子出发,一直沿着指向左子结点的指针找到的叶子节点即为下一个节点;
- 3.节点不是根节点。如果该节点是其父节点的左孩子,则返回父节点;否则继续向上遍历其父节点的父节点,重复之前的判断,返回结果。代码如下:
class Solution:
def GetNext(self, pNode):
# write code here
if not pNode:
return None
if pNode.right:
tmp=pNode.right
while tmp.left:
tmp=tmp.left
return tmp
while pNode.next:
father=pNode.next
if father.left == pNode:
return father
else:
pNode=father
return None
对称的二叉树
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
- 当前结点左右结点是否相等
- left.left == right.right ? left.right == right.left ?
class Solution:
def isSymmetrical(self, pRoot):
# write code here
if not pRoot:
return True
return self.compare(pRoot.left,pRoot.right)
def compare(self,left,right):
if not left and not right:
return True
if not left or not right:
return False
if left.val == right.val:
return self.compare(left.left,right.right) and self.compare(left.right,right.left)
else:
return False