93. 平衡二叉树
题目
给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
您在真实的面试中是否遇到过这个题? Yes
样例
给出二叉树 A={3,9,20,#,#,15,7}, B={3,#,20,15,7}
A) 3 B) 3
/ \ \
9 20 20
/ \ / \
15 7 15 7
二叉树A是高度平衡的二叉树,但是B不是
思路
- 每得到一个节点就去判断它的左右子树深度相差是否大于1
- 所以先定义一个计算深度的函数。
代码
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: The root of binary tree.
@return: True if this Binary tree is Balanced, or false.
"""
def isBalanced(self, root):
# write your code here
if root is None:return True
left_depth = self.getDepth(root.left)
right_depth = self.getDepth(root.right)
#之间左右子树深度的差值
cha = left_depth - right_depth
#相差大于1非平衡二叉树
if abs(cha)>1:
return False
#下面节点的左右子树
return self.isBalanced(root.right) and self.isBalanced(root.left)
#深度的计算
def getDepth(self,Root):
if Root is None:return 0
left_depth = self.getDepth(Root.left)
right_depth = self.getDepth(Root.right)
return max(left_depth,right_depth)+1
165. 合并两个排序链表
题目
将两个排序链表合并为一个新的排序链表
样例
给出 1->3->8->11->15->null,2->null, 返回 1->2->3->8->11->15->null。
思路
- 这类似于两个列表进行合并,并且原列表还是有序
- 直接使用新的链表,来接收值小的
代码
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param two ListNodes
@return a ListNode
"""
def mergeTwoLists(self, l1, l2):
# write your code here
if l1 is None : return l2
if l2 is None : return l1
#新建一个链表,存放结果
l3 = ListNode(0)
new = l3
while l1 is not None and l2 is not None:
if l1.val < l2.val:
new.next = l1
l1 = l1.next
else:
new.next = l2
l2 = l2.next
#下一个节点
new = new.next
#将另外一个不是None的值接着添加到new
if l1 is None:
new.next = l2
else:
new.next = l1
#不可以return new.next这样子的话不是从一开始
return l3.next
453. 将二叉树拆成链表
题目
将一棵二叉树按照前序遍历拆解成为一个假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。
注意事项
不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。
样例
‘
1
\
1 2
/ \ \
2 5 => 3
/ \ \ \
3 4 6 4
\
5
\
6
思路
- 先得到这个二叉树的前序遍历的列表
- 将列表一个一个装进假链表中(树),其中所有的左子树 = None,所以需要对列表的值成数的节点。
代码
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param: root: a TreeNode, the root of the binary tree
@return:
"""
def flatten(self, root):
# write your code here
#得到前序列表
list1=[]
self.preorderTraversal(root,list1)
x = root
for i in list1[1:]:
#将列表的值变成树
ss = TreeNode(i)
x.left = None
x.right = ss
#指向下一个右即next
x = x.right
#前序
def preorderTraversal(self, root,list1=[]):
# write your code here
if root is not None:
list1.append(root.val)
self.preorderTraversal(root.left,list1)
self.preorderTraversal(root.right,list1)
return list1