11、合并两个排序的链表
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
划重点:参加旷视科技宣讲会现场面试遇到这道题,原题,。。。可是那个时候还没刷到,还是刷题太少了,评论区好多刷了600+、300+的
自己当时解题思路太简单了,主要没有算法知识,不懂链表(捂脸),当时想的是列表合并,sort函数排序。。。
解法1:
评论区看到的,递归和非递归版本
链接:https://www.nowcoder.com/questionTerminal/d8b6b4358f774294a89de2a6ac4d9337
来源:牛客网
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
p = pHead = ListNode(0)
while pHead1 and pHead2:
if pHead1.val < pHead2.val:
pHead.next = pHead1
pHead1 = pHead1.next
pHead = pHead.next
else:
pHead.next = pHead2
pHead2 = pHead2.next
pHead = pHead.next
if pHead1:
pHead.next = pHead1
if pHead2:
pHead.next = pHead2
return p.next
链接:https://www.nowcoder.com/questionTerminal/d8b6b4358f774294a89de2a6ac4d9337
来源:牛客网
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
if pHead1 is None:
return pHead2
if pHead2 is None:
return pHead1
if pHead1.val < pHead2.val:
pHead1.next = self.Merge(pHead1.next,pHead2)
return pHead1
else:
pHead2.next = self.Merge(pHead1,pHead2.next)
return pHead2
12、树的子结构
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
思路:看评论的,感谢大家的解答~
链接:https://www.nowcoder.com/questionTerminal/6e196c44c7004d15b1610b9afca8bd88
来源:牛客网
1、首先设置标志位result = false,因为一旦匹配成功result就设为true,
剩下的代码不会执行,如果匹配不成功,默认返回false
2、递归思想,如果根节点相同则递归调用DoesTree1HaveTree2(),
如果根节点不相同,则判断tree1的左子树和tree2是否相同,
再判断右子树和tree2是否相同
3、注意null的条件,HasSubTree中,如果两棵树都不为空才进行判断,
DoesTree1HasTree2中,如果Tree2为空,则说明第二棵树遍历完了,即匹配成功,
tree1为空有两种情况(1)如果tree1为空&&tree2不为空说明不匹配,
(2)如果tree1为空,tree2为空,说明匹配
链接:https://www.nowcoder.com/questionTerminal/6e196c44c7004d15b1610b9afca8bd88
来源:牛客网
其中需要注意的是:
- 测试用例如果pRoot2为空的话,返回的false而不是我们认为的空树应该是所有树的子树
- 再判断是否子树的过程中,应该先判断pRoot2是否为空,为空则表明子树的所有节点都比较完了,应该是子树返回True
- 要养成一个习惯,对任何一个树节点进行访问时,一定要提前检测该节点是否为空
-*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
if not pRoot1 or not pRoot2:
return False
return self.is_subtree(pRoot1,pRoot2) or self.is_subtree(pRoot1.left,pRoot2) or self.is_subtree(pRoot1.right,pRoot2)
def is_subtree(self,A,B):
if not B:
return True
if not A or A.val != B.val:
return False
return self.is_subtree(A.left,B.left) and self.is_subtree(A.right, B.right)
13、二叉树的镜像
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/
6 10
/ \ /
5 7 9 11
镜像二叉树
8
/
10 6
/ \ /
11 9 7 5
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
# write code here
if not root:
return root
if not root.right and not root.left:
return root
if root.right or root.left:
t=root.right
root.right=root.left
root.left=t
self.Mirror(root.right)
self.Mirror(root.left)
return root