编程集训第4天:LeetCode验证二叉搜索树(98)及二叉树层次遍历(102,107)
基础知识
1 二叉树的定义
二叉树是每个节点最多有两个子树的树结构。
2 遍历
二叉树遍历:前序遍历、中序遍历、后序遍历3种方式。
2.1 前序遍历
若二叉树非空,则执行以下操作:
(01) 访问根结点;
(02) 先序遍历左子树;
(03) 先序遍历右子树。
2.2 中序遍历
若二叉树非空,则执行以下操作:
(01) 中序遍历左子树;
(02) 访问根结点;
(03) 中序遍历右子树。
2.3 后序遍历
若二叉树非空,则执行以下操作:
(01) 后序遍历左子树;
(02) 后序遍历右子树;
(03) 访问根结点。
对于上面的二叉树而言,
(01) 前序遍历结果: 3 1 2 5 4 6
(02) 中序遍历结果: 1 2 3 4 5 6
(03) 后序遍历结果: 2 1 4 6 5 3
编程题目
题目描述:
98. 验证二叉搜索树
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
思路: 采用递归的思路,判断当前节点,是否比左子节点大,是否比右节点小,若不是输出false,如果判断成立,继续以左边子节点和右子边节点为当前节点,继续检测,最后递归到None的层级仍然判断成立,返回Ture。
python:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def validBST(self,root,small,large):
if root==None:
return True
if small>=root.val or large<=root.val:
return False
return self.validBST(root.left,small,root.val) and self.validBST(root.right,root.val,large)
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.validBST(root,-2**32,2**32-1)
102.二叉树的层次遍历
给定一个二叉树,返回其按层次遍历的节点值。(即逐层地,从左到右访问所有节点)。
例如:
给定二叉树: [3,9,20,null,null,15,7]
思路: 采用队列的思想,(1)将当前节点加入queue中,(2)queue中有多少个元素,将每个元素pop出queue并加入到 res[],(3)再将每个元素的左右子节点加入到queue中,递归循环。
python:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
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
107.二叉树的层次遍历 II
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
思路:思路与上题类似,加入到res[]的时候是往前插入。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(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 = [templist] + res
return res