一、二叉树
二叉树是树的特殊一种,具有如下特点:1、每个结点最多有两颗子树,结点的度最大为2。2、左子树和右子树是有顺序的,次序不能颠倒。3、即使某结点只有一个子树,也要区分左右子树。
二叉树性质:
1、在非空二叉树的i层上,至多有2i-1个节点(i>=1)。通过归纳法论证。
2、在深度为K的二叉树上最多有2k-1个结点(k>=1)。通过归纳法论证。
3、对于任何一棵非空的二叉树,如果叶节点个数为n0,度数为2的节点个数为n2,则有: n0 = n2 + 1在一棵二叉树中,除了叶子结点(度为0)之外,就剩下度为2(n2)和1(n1)的结点了。则树的结点总数为T = n0+n1+n2;在二叉树中结点总数为T,而连线数为T-1.所以有:n0+n1+n2-1 = 2*n2 +n1;最后得到n0 = n2+1;
二、练习
leetcode98
1)题目
2)答案
class Solution(object):
pre=None
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
Bool= self.isValidBST(root.left)
if self.pre!=None:
Bool=Bool and (self.pre.val<root.val)
self.pre=root
Bool=Bool and self.isValidBST(root.right)
return Bool
3)分析
为Solution类添加pre数据成员,在中序遍历二叉搜索树的过程中,pre用来指向当前节点的前驱节点。
注意:pre不能放在isValidBST函数的内部。如果将pre放在isValidBST函数的内部,则每一次递归调用isValidBST函数的时候,pre都将重新赋值为None。实际上,在每一次递归调用时,我们需要的是上一次调用结束时pre的值’’’
leetcode102
1)题目
2)答案
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
queue = [root]
res = []
if not root:
return []
while queue:
templist = []
templen =len(queue)
for i in range(templen):
temp = queue.pop(0)
templist.append(temp.val)
if temp.left:
queue.append(temp.left)
if temp.right:
queue.append(temp.right)
res.append(templist)
return res
3)分析
用队列实现:root为空,则返回空表,队列不为空,记下此时队列中的结点个数temp,temp个结点出队列的同时,记录结点值,并把结点的左右子结点加入队列
leetcode107
1)题目
2)答案
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
queue=[root]
res=[]
while queue:
nodes=[]
node_values=[]
for node in queue:
if node.left:
nodes.append(node.left)
if node.right:
nodes.append(node.right)
node_values+=[node.val]
res=[node_values]+res
queue=nodes
return res