二叉树的种类
在我们解题过程中二叉树有两种主要的形式:满二叉树和完全二叉树。
满二叉树
满二叉树:如果一棵二叉树只有度为0的结点和度为2的结点,并且度为0的结点在同一层上,则这棵二叉树为满二叉树。
如图所示:
这棵二叉树为满二叉树,也可以说深度为k,有2^k-1个节点的二叉树。
完全二叉树
什么是完全二叉树?
完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2^(h-1) 个节点。
之前说过优先级队列(PriorityQueue(优先队列)_EvilChou的博客-CSDN博客)其实是一个堆,堆就是一棵完全二叉树,同时保证父子节点的顺序关系。
二叉树的高度和深度
求二叉树深度 和 二叉树高度的差异,求深度适合用前序遍历,而求高度适合用后序遍历。
高度和深度定义
(对某个节点来说)
深度是指从根节点到该节点的最长简单路径边的条数;
高度是指从最下面的叶子节点到该节点的最长简单路径边的条数;
(对二叉树)
深度是从根节点数到它的叶节点;
高度是从叶节点数到它的根节点;
注意: 树的深度和高度一样,但是具体到树的某个节点,其深度和高度不一样;同一层的节点的深度是相同,但是高度不一定相同。最大深度:
最大深度是从根节点到最近叶子节点的最长路径上的节点数量。
最小深度:
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
如图:树的高度和深度都为4(看层数);节点8的深度为3;节点9的高度为2
例题:设某棵二叉树的高度为10,则该二叉树上叶子结点最多有 512 个
高度为10,说明该二叉树有10层
第一层的结点个数为2的0次幂,第二层的结点个数最多为2的1次幂,依次类推
第k层上的结点最多为2的(k-1)次幂,将10带入k,得到结果2的9次幂,so第10层最多有512个结点
即该二叉树最多有512个叶子结点。
二叉搜索树
前面介绍的树,都没有数值的,而二叉搜索树是有数值的了,二叉搜索树是一个有序树。
- 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
- 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
- 它的左、右子树也分别为二叉排序树
下面这两棵树都是搜索树
平衡二叉搜索树
平衡二叉搜索树:又被称为AVL(Adelson-Velsky and Landis)树,且具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
如图:
最后一棵 不是平衡二叉树,因为它的左右两个子树的高度差的绝对值超过了1。
有同学会把红黑树和二叉平衡搜索树弄分开了,其实红黑树就是一种平衡二叉搜索树,这两个树不是独立的,所以C++中map、multimap、set、multiset的底层实现机制是二叉平衡搜索树,再具体一点是红黑树,所以map、set的增删操作时间时间复杂度是logn,注意这里没有说unordered_map、unordered_set,它们底层实现是哈希表。
所以使用自己熟悉的编程语言写算法,一定要知道常用的容器底层都是如何实现的,最基本的就是map、set等等,否则自己写的代码,自己对其性能分析都分析不清楚!
二叉树的存储方式
二叉树可以链式存储,也可以顺序存储。
那么链式存储方式就用指针, 顺序存储的方式就是用数组。
顾名思义就是顺序存储的元素在内存是连续分布的,而链式存储则是通过指针把分布在散落在各个地址的节点串联一起。
链式存储如图:
常用的链式存储如下图所示:
链式存储是大家很熟悉的一种方式,那么我们来看看如何顺序存储呢?
其实就是用数组来存储二叉树,顺序存储的方式如图:
用数组来存储二叉树如何遍历的呢?
如果父节点的数组下标是 i,那么它的左孩子就是 i * 2 + 1,右孩子就是 i * 2 + 2。
但是用链式表示的二叉树,更有利于我们理解,所以一般我们都是用链式存储二叉树。
所以大家要了解,用数组依然可以表示二叉树。
二叉树的遍历方式
关于二叉树的遍历方式,要知道二叉树遍历的基本方式都有哪些。
二叉树主要有两种遍历方式:
- 深度优先遍历:先往深走,遇到叶子节点再往回走。
- 广度优先遍历:一层一层的去遍历。
这两种遍历是图论中最基本的两种遍历方式。
那么从深度优先遍历和广度优先遍历进一步拓展,才有如下遍历方式:
- 深度优先遍历
- 前序遍历(递归法,迭代法)
- 中序遍历(递归法,迭代法)
- 后序遍历(递归法,迭代法)
- 广度优先遍历
- 层次遍历(迭代法)
在深度优先遍历中:有三个顺序,前中后序遍历, 这里前中后,其实指的就是中间节点的遍历顺序,只要记住 前中后序指的就是中间节点的位置就可以了。
看如下中间节点的顺序,就可以发现,中间节点的顺序就是所谓的遍历方式
- 前序遍历:中左右
- 中序遍历:左中右
- 后序遍历:左右中
最后再说一说二叉树中深度优先和广度优先遍历实现方式,我们做二叉树相关题目,经常会使用递归的方式来实现深度优先遍历,也就是实现前中后序遍历,使用递归是比较方便的。
之前讲栈与队列的时候,就说过栈其实就是递归的一种是实现结构,也就说前中后序遍历的逻辑其实都是可以借助栈使用非递归的方式来实现的。
而广度优先遍历的实现一般使用队列来实现,这也是队列先进先出的特点所决定的,因为需要先进先出的结构,才能一层一层的来遍历二叉树。
这里其实我们又了解了栈与队列的一个应用场景了。
二叉树的定义
刚刚我们说过了二叉树有两种存储方式顺序存储,和链式存储,顺序存储就是用数组来存,这个定义没啥可说的,我们来看看链式存储的二叉树节点的定义方式。
C++代码如下:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
大家会发现二叉树的定义 和链表是差不多的,相对于链表 ,二叉树的节点里多了一个指针, 有两个指针,指向左右孩子。
Java代码如下:
public class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {this.val = val;}
TreeNode(int val, TreeNode left, TreeNode right){
this.val = val;
this.left = left;
this.right = right;
}
}
二叉树的递归遍历
递归算法的三个要素。每次写递归,都按照这三要素来写,可以保证写出正确的递归算法!
-
确定递归函数的参数和返回值: 确定哪些参数是递归的过程中需要处理的,那么就在递归函数里加上这个参数, 并且还要明确每次递归的返回值是什么进而确定递归函数的返回类型。
-
确定终止条件: 写完了递归算法, 运行的时候,经常会遇到栈溢出的错误,就是没写终止条件或者终止条件写的不对,操作系统也是用一个栈的结构来保存每一层递归的信息,如果递归没有终止,操作系统的内存栈必然就会溢出。
-
确定单层递归的逻辑: 确定每一层递归需要处理的信息。在这里也就会重复调用自己来实现递归的过程。
以下以前序遍历(Java)为例:
- 确定递归函数的参数和返回值:因为要打印出前序遍历节点的数值,所以参数里需要传入list在放节点的数值,除了这一点就不需要在处理什么数据了也不需要有返回值,所以递归函数返回类型就是void,代码如下:
public void preorder(TreeNode root, list<Integer> result)
- 确定终止条件:在递归的过程中,如何算是递归结束了呢,当然是当前遍历的节点是空了,那么本层递归就要要结束了,所以如果当前遍历的这个节点是空,就直接return,代码如下:
if (root == NULL) return;
- 确定单层递归的逻辑:前序遍历是中左右的循序,所以在单层递归的逻辑,是要先取中节点的数值,代码如下:
result.add(root.val); // 中
preorder(root.left, result); // 左
preorder(root.right, result); // 右
单层递归的逻辑就是按照中左右的顺序来处理的,这样二叉树的前序遍历,基本就写完了,再看一下完整代码:
前序遍历(递归法)
class Solution{
public List<Integer> preorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
preorder(root, result);
return result;
}
public void preorder(TreeNode root, List<Integer> list){
if(root == null){
return;
}
list.add(root.val);
preorder(root.left, list);
preorder(root.right, list);
}
}
那么前序遍历写出来之后,中序和后序遍历就不难理解了,代码如下:
中序遍历(递归法)
class Solution{
public List<Integer> inorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
inorder(root, result);
return result;
}
public void inorder(TreeNode root, List<Integer> list){
if(root == null){
return;
}
inorder(root.left, list);
result.add(root.val);
inorder(root.right, list);
}
}
后序遍历(递归法)
class Solution{
public List<Integer> postorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
postorder(root, result);
return result;
}
public void postorder(TreeNode root, List<Integer> list){
if(root == null){
return;
}
postorder(root.left, list);
postorder(root.right, list);
result.add(root.val);
}
}
二叉树的迭代遍历
递归的实现就是:每一次递归调用都会把函数的局部变量、参数值和返回地址等压入调用栈中,然后递归返回的时候,从栈顶弹出上一次递归的各项参数,所以这就是递归为什么可以返回上一层位置的原因。
此时大家应该知道我们用栈也可以是实现二叉树的前后中序遍历了。
前序遍历(迭代法)
我们先看一下前序遍历。
前序遍历是中左右,每次先处理的是中间节点,那么先将根节点放入栈中,然后将右孩子加入栈,再加入左孩子。
为什么要先加入 右孩子,再加入左孩子呢? 因为这样出栈的时候才是中左右的顺序。
动画如下:
不难写出如下代码: (注意代码中空节点不入栈)
class Solution{
public List<Integer> preorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
if(root == null){
return result;
}
Deque<TreeNode> stack = new LinkedList<>();
//Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
result.add(node.val);
if(node.right != null){
stack.push(node.right);
}
if(node.left != null){
stack.push(node.left);
}
}
return result;
}
}
此时是不是想改一点前序遍历代码顺序就把中序遍历搞出来了?
其实还真不行!
但接下来,再用迭代法写中序遍历的时候,会发现套路又不一样了,目前的前序遍历的逻辑无法直接应用到中序遍历上。
中序遍历(迭代法)
为了解释清楚,说明一下刚刚在迭代的过程中,其实我们有两个操作:
- 处理:将元素放进result数组中
- 访问:遍历节点
分析一下为什么刚刚写的前序遍历的代码,不能和中序遍历通用呢,因为前序遍历的顺序是中左右,先访问的元素是中间节点,要处理的元素也是中间节点,所以刚刚才能写出相对简洁的代码,因为要访问的元素和要处理的元素顺序是一致的,都是中间节点。
那么再看看中序遍历,中序遍历是左中右,先访问的是二叉树顶部的节点,然后一层一层向下访问,直到到达树左面的最底部,再开始处理节点(也就是在把节点的数值放进result数组中),这就造成了处理顺序和访问顺序是不一致的。
那么在使用迭代法写中序遍历,就需要借用指针的遍历来帮助访问节点,栈则用来处理节点上的元素。
动画如下:
中序遍历,可以写出如下代码:
class Solution{
public List<Integer> inorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
if(root == null){
return result;
}
Deque<TreeNode> stack = new LinkedList<>();
TreeNode node = root;
while(node != null || !stack.isEmpty()){
if(node != null){
stack.push(node);
node = node.left;
}else{
node = stack.pop();
result.add(node.val);
node = node.right;
}
}
return result;
}
}
后序遍历(迭代法)
再来看后序遍历,先序遍历是中左右,后续遍历是左右中,那么我们只需要调整一下先序遍历的代码顺序,就变成中右左的遍历顺序,然后在反转result数组,输出的结果顺序就是左右中了,如下图:
所以后序遍历只需要前序遍历的代码稍作修改就可以了,代码如下:
class Solution{
public List<Integer> postorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
if(root == null){
return result;
}
Deque<TreeNode> stack = new LinkedList<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
result.add(node.val);
if(node.left != null){
stack.push(node.left);
}
if(node.right != null){
stack.push(node.right);
}
}
Collections.reverse(result);
return result;
}
}
此时我们用迭代法写出了二叉树的前后中序遍历,大家可以看出前序和中序是完全两种代码风格,并不像递归写法那样代码稍做调整,就可以实现前后中序。
这是因为前序遍历中访问节点(遍历节点)和处理节点(将元素放进result数组中)可以同步处理,但是中序就无法做到同步!
那么问题又来了,难道二叉树前后中序遍历的迭代法实现,就不能风格统一么(即前序遍历改变代码顺序就可以实现中序和后序)?
二叉树的统一迭代法
我们发现迭代法实现的先中后序,其实风格也不是那么统一,除了先序和后序,有关联,中序完全就是另一个风格了,一会用栈遍历,一会又用指针来遍历。
实践过的同学,也会发现使用迭代法实现先中后序遍历,很难写出统一的代码,不像是递归法,实现了其中的一种遍历方式,其他两种只要稍稍改一下节点顺序就可以了。
其实针对三种遍历方式,使用迭代法是可以写出统一风格的代码!
重头戏来了,接下来介绍一下统一写法。
中序遍历为例,使用栈的话,无法同时解决访问节点(遍历节点)和处理节点(将元素放进结果集)不一致的情况。
那我们就将访问的节点放入栈中,把要处理的节点也放入栈中但是要做标记。
如何标记呢,就是要处理的节点放入栈之后,紧接着放入一个空指针作为标记。 这种方法也可以叫做标记法。
来看一下动画(中序遍历):
动画中,result数组就是最终结果集。
可以看出我们将访问的节点直接加入到栈中,但如果是处理的节点则后面放入一个空节点, 这样只有空节点弹出的时候,才将下一个节点放进结果集。
此时我们再来看中序遍历代码。
统一迭代法中序遍历
class Solution{
public List<Integer> inorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
if(root != null) stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.peek();
if(node != null){
stack.pop();// 将该节点弹出,避免重复操作,下面再将右中左节点添加到栈中
if(node.right != null) stack.push(node.right);// 添加右节点(空节点不入栈)
stack.push(node);// 添加中节点
stack.push(null);// 中节点访问过,但是还没有处理,加入空节点做为标记
if(node.left != null) stack.push(node.left);// 添加左节点(空节点不入栈)
}else{// 只有遇到空节点的时候,才将下一个节点放进结果集
stack.pop();// 将空节点弹出
node = stack.peek();// 重新取出栈中元素
stack.pop();
result.add(node.val);// 加入到结果集
}
}
return result;
}
}
统一迭代法前序遍历
迭代法前序遍历代码如下: (注意此时我们和中序遍历相比仅仅改变了两行代码的顺序)
class Solution{
public List<Integer> preorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
if(root == null) stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.peek();
if(node != null){
stack.pop();
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
stack.push(node);
stack.push(null);
}else{
stack.pop();
node = stack.peek();
stack.pop();
result.add(node.val);
}
}
return result;
}
}
例:N叉树的前序遍历
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
/**
//递归法
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> result = new ArrayList<>();
preorderTraversal(root, result);
return result;
}
private void preorderTraversal(Node node, List<Integer> list){
if(node == null) return;
list.add(node.val);
for(Node child : node.children){
preorderTraversal(child, list);
}
}
}
*/
//迭代法
class Solution {
public List<Integer> preorder(Node root) {
List<Integer> result = new ArrayList<>();
Deque<Node> stack = new LinkedList<>();
if(root != null) stack.push(root);
while(!stack.isEmpty()){
Node node = stack.peek();
if(node != null){
stack.pop();
//所有子节点从右向左逆序压入栈中,这样出栈的节点则是顺序从左向右的
for(int i = node.children.size() - 1; i >= 0; i--){
stack.push(node.children.get(i));
}
stack.push(node);
stack.push(null);
}else{
stack.pop();
node = stack.peek();
stack.pop();
result.add(node.val);
}
}
return result;
}
}
首先把根节点入栈,因为根节点是前序遍历中的第一个节点。随后每次我们从栈顶取出一个节点 u,它是我们当前遍历到的节点,并把 u 的所有子节点从右向左逆序压入栈中,这样出栈的节点则是顺序从左向右的。例如 u 的子节点从左到右为 v1, v2, v3,那么入栈的顺序应当为 v3, v2, v1,这样就保证了下一个遍历到的节点(即 u 的左侧第一个孩子节点 v1)出现在栈顶的位置。此时,访问第一个子节点 v1时,仍然按照此方法则会先访问 v1的左侧第一个孩子节点。
统一迭代法后序遍历
后续遍历代码如下: (注意此时我们和中序遍历相比仅仅改变了两行代码的顺序)
class Solution{
public postorderTraversal(TreeNode root){
List<Integer> result = new ArrayList<>();
Deque<TreeNode> stack = new LinkedList<>();
if(root != null) stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.peek();
if(node != null){
stack.pop();
stack.push(node);
stack.push(null);
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}else{
stack.pop();
node = stack.peek();
stack.pop();
result.add(node.val);
}
}
return result;
}
}
例:N叉树的后序遍历
//递归法
class Solution {
public List<Integer> postorder(Node root) {
List<Integer> result = new ArrayList<>();
postorderTraversal(root, result);
return result;
}
private void postorderTraversal(Node node, List<Integer> list){
if(node == null) return;
for(Node child : node.children){
postorderTraversal(child, list);
}
list.add(node.val);
}
}
//迭代法
class Solution {
public List<Integer> postorder(Node root) {
List<Integer> result = new ArrayList<>();
Deque<Node> stack = new LinkedList<>();
if(root != null) stack.push(root);
while(!stack.isEmpty()){
Node node = stack.peek();
if(node != null){
stack.pop();
stack.push(node);
stack.push(null);
//所有子节点从右向左逆序压入栈中,这样出栈的节点则是顺序从左向右的
for(int i = node.children.size() - 1; i >= 0; i--){
stack.push(node.children.get(i));
}
}else{
stack.pop();
node = stack.peek();
stack.pop();
result.add(node.val);
}
}
return result;
}
}
二叉树的层序遍历
层序遍历一个二叉树。就是从左到右一层一层的去遍历二叉树。这种遍历的方式和之前讲过的都不太一样。
需要借用一个辅助数据结构即队列来实现,队列先进先出,符合一层一层遍历的逻辑,而栈先进后出适合模拟深度优先遍历也就是递归的逻辑。
而这种层序遍历方式就是图论中的广度优先遍历,只不过我们应用在二叉树上。
使用队列实现二叉树广度优先遍历,动画如下:
这样就实现了层序从左到右遍历二叉树。
迭代法层序遍历
class Solution{
public List<List<Integer>> levelOrder(TreeNode root){
List<List<Integer>> resList = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root != null) queue.offer(root);
while(!queue.isEmpty()){
List<Integer> itemList = new ArrayList<>();
int len = queue.size();
for(int i = 0; i < len; i++){
TreeNode node = queue.poll();
itemList.add(node.val);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
resList.add(itemList);
}
return resList;
}
}
递归法层序遍历
class Solution {
public List<List<Integer>> resList = new ArrayList<List<Integer>>();
public List<List<Integer>> levelOrder(TreeNode root) {
checkFun01(root,0);
return resList;
}
//DFS--递归方式
public void checkFun01(TreeNode node, Integer deep) {
if (node == null) return;
deep++;
if (resList.size() < deep) {
//当层级增加时,list的Item也增加,利用list的索引值进行层级界定
List<Integer> item = new ArrayList<Integer>();
resList.add(item);
}
resList.get(deep - 1).add(node.val);
checkFun01(node.left, deep);
checkFun01(node.right, deep);
}
}
层序遍历相关题目
例1.二叉树的层序遍历II
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
//从上到下层序遍历二叉树后,再反转数组
List<List<Integer>> resList = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root != null) queue.offer(root);
while(!queue.isEmpty()){
List<Integer> itemList = new ArrayList<>();
int len = queue.size();
for(int i = 0; i < len; i++){
TreeNode node = queue.poll();
itemList.add(node.val);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
resList.add(itemList);
}
List<List<Integer>> result = new ArrayList<>();
for(int i = resList.size() - 1; i >= 0; i--){
result.add(resList.get(i));
}
return result;
}
}
例2.二叉树的右视图
class Solution{
public List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root != null) queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
for(int i = 0; i < len; i++){
TreeNode node = queue.poll();
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
if(i == len - 1) result.add(node.val);
}
}
return result;
}
}
例3.二叉树的层平均值
class Solution{
public List<Double> averageOfLevels(TreeNode root) {
List<Double> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root != null) queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
double sum = 0.0;//double类型
for(int i = 0; i < len; i++){
TreeNode node = queue.poll();
sum += node.val;
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
result.add(sum / len);
}
return result;
}
}
例4.N叉树的层序遍历
class Solution{
public List<List<Integer>> levelOrder(Node root){
List<List<Integer>> resList = new ArrayList<>();
Queue<Node> queue = new LinkedList<>(); //非TreeNode
if(root != null) queue.offer(root);
while(!queue.isEmpty()){
List<Integer> itemList = new ArrayList<>();
int len = queue.size();
for(int i = 0; i < len; i++){
Node cur = queue.poll();
itemList.add(cur.val);
//添加根结点的子节点
for(Node child : cur.children){
queue.offer(child);
}
}
resList.add(itemList);
}
return resList;
}
}
例5.在每个树行中找最大值
class Solution{
public List<Integer> largestValues(TreeNode root){
List<Integer> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
if(root != null) queue.offer(root);
While(!queue.isEmpty()){
int len = queue.size();
int max = Integer.MAX_VALUE;
for(int i = 0; i < len; i++){
TreeNode node = queue.poll();
max = Math.max(max, node.val);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
result.add(max);
}
return result;
}
}
例6.填充每个节点的下一个右侧节点指针
class Solution{
public Node connect(Node root){
Queue<Node> queue = new LinkedList<>();
if(root != null) queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
for(int i = 0; i < len; i++){
Node node = queue.poll();
if(i < len - 1) node.next = queue.peek();//初始状态下,所有next指针都被设置为 NULL
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}
return root;
}
}
例7.二叉树的最大深度
//迭代法:中序遍历
class Solution{
public int maxDepth(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
if(root != null) queue.offer(root);
int maxDepth = 0;
while(!queue.isEmpty()){
int len = queue.size();
for(int i = 0; i < len; i++){
TreeNode node = queue.poll();
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
maxDepth++:
}
return maxDepth;
}
}
//递归法
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1; //先求它的左子树的深度,再求的右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度
}
}
//迭代法:前序遍历
class Solution {
int result;
public int maxDepth(TreeNode root) {
result = 0;
if(root == null) return result;
getDepth(root, 1);
return result;
}
private void getDepth(TreeNode node, int depth){
result = depth > result ? depth : result; //中
if(node.left == null && node.right == null) return;
if(node.left != null){ //左
/**
depth++;//深度+1
getDepth(node.left, depth);
depth--;//回溯, 深度-1
*/
getDepth(node.left, depth + 1);
}
if(node.right != null){
/**
depth++;
getDepth(node.right, depth);
depth--;
*/
getDepth(node.right, depth + 1);
}
return;
}
}
//迭代法:后序遍历
class Solution {
public int maxDepth(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
if(root != null) stack.push(root);
int maxDepth = 0;
int result = 0;
while(!stack.isEmpty()){
TreeNode node = stack.peek();
if(node != null){
stack.pop();
stack.push(node);
stack.push(null);
maxDepth++;
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}else{
stack.pop();
node = stack.peek();
stack.pop();
maxDepth--;
}
result = result > maxDepth ? result : maxDepth;
}
return result;
}
}
例8.二叉树的最小深度
//迭代法
class Solution {
public int minDepth(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
if(root != null) queue.offer(root);
int minDepth = 0;
while(!queue.isEmpty()){
int len = queue.size();
minDepth++;
for(int i = 0; i < len; i++){
TreeNode node = queue.poll();
if(node.left == null && node.right == null){
return minDepth;
}
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}
return minDepth;
}
}
//递归法1:
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null) return 1;
int min_Depth = Integer.MAX_VALUE;
if(root.left != null){
min_Depth = Math.min(min_Depth, minDepth(root.left));
}
if(root.right != null){
min_Depth = Math.min(min_Depth, minDepth(root.right));
}
return min_Depth + 1;
}
}
//递归法2:如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。
//反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。
//最后如果左右子树都不为空,返回左右子树深度最小值 + 1
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
if (root.left == null) {
return rightDepth + 1;
}
if (root.right == null) {
return leftDepth + 1;
}
// 左右结点都不为null
return Math.min(leftDepth, rightDepth) + 1;
}
}
翻转二叉树
遍历的过程中去翻转每一个节点的左右孩子就可以达到整体翻转的效果。
注意只要把每一个节点的左右孩子翻转一下,就可以达到整体翻转的效果
这道题目使用前序遍历和后序遍历都可以,唯独中序遍历不方便,因为中序遍历会把某些节点的左右孩子翻转了两次!建议拿纸画一画,就理解了
那么层序遍历可以不可以呢?依然可以的!只要把每一个节点的左右孩子翻转一下的遍历方式都是可以的!
递归法
我们下文以前序遍历为例,通过动画来看一下翻转的过程:
我们来看一下递归三部曲:
确定递归函数的参数和返回值
参数就是要传入节点的指针,不需要其他参数了,通常此时定下来主要参数,如果在写递归的逻辑中发现还需要其他参数的时候,随时补充。
返回值的话其实也不需要,但是题目中给出的要返回root节点的指针,可以直接使用题目定义好的函数,所以就函数的返回类型为TreeNode
。
TreeNode invertTree(TreeNode root)
确定终止条件
当前节点为空的时候,就返回
if(root == null) return null;
确定单层递归的逻辑
因为是先前序遍历,所以先进行交换左右孩子节点,然后反转左子树,反转右子树。
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
基于这递归三步法,代码基本写完,如下:
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
迭代法
深度优先遍历(前序遍历)
class Solution {
public TreeNode invertTree(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
if(root != null) stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.peek();
if(node != null){
stack.pop();
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
stack.push(node);
stack.push(null);
}else{
stack.pop();
node = stack.peek();
stack.pop();
swap(node);
}
}
return root;
}
private void swap(TreeNode node){
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
}
广度优先遍历
也就是层序遍历,层数遍历也是可以翻转这棵树的,因为层序遍历也可以把每个节点的左右孩子都翻转一遍,代码如下:
class Solution {
public TreeNode invertTree(TreeNode root) {
//广度优先搜索:中序遍历迭代方法
Queue<TreeNode> queue = new LinkedList<>();
if(root != null) queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
for(int i = 0; i < len; i++){
TreeNode node = queue.poll();
swap(node);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}
return root;
}
private void swap(TreeNode node){
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
}
对称二叉树
首先想清楚,判断对称二叉树要比较的是哪两个节点,要比较的可不是左右节点!
对于二叉树是否对称,要比较的是根节点的左子树与右子树是不是相互翻转的,理解这一点就知道了其实我们要比较的是两个树(这两个树是根节点的左右子树),所以在递归遍历的过程中,也是要同时遍历两棵树。
那么如果比较呢?
比较的是两个子树的里侧和外侧的元素是否相等。如图所示:
那么遍历的顺序应该是什么样的呢?
本题遍历只能是“后序遍历”,因为我们要通过递归函数的返回值来判断两个子树的内侧节点和外侧节点是否相等。
正是因为要遍历两棵树而且要比较内侧和外侧节点,所以准确的来说是一个树的遍历顺序是左右中,一个树的遍历顺序是右左中。
但都可以理解算是后序遍历,尽管已经不是严格上在一个树上进行遍历的后序遍历了。
递归法
递归三部曲
确定递归函数的参数和返回值
因为我们要比较的是根节点的两个子树是否是相互翻转的,进而判断这个树是不是对称树,所以要比较的是两个树,参数自然也是左子树节点和右子树节点。
返回值自然是bool类型。
代码如下:
boolean compare(TreeNode left, TreeNode right)
确定终止条件
要比较两个节点数值相不相同,首先要把两个节点为空的情况弄清楚!否则后面比较数值的时候就会操作空指针了。
节点为空的情况有:(注意我们比较的其实不是左孩子和右孩子,所以如下我称之为左节点右节点)
- 左节点为空,右节点不为空,不对称,return false
- 左不为空,右为空,不对称 return false
- 左右都为空,对称,返回true
此时已经排除掉了节点为空的情况,那么剩下的就是左右节点不为空:
- 左右都不为空,比较节点数值,不相同就return false
此时左右节点不为空,且数值也不相同的情况我们也处理了。
代码如下:
if(left == null && right != null) return false;
if(left != null && right == null) return false;
if(left == null && right == null) return true;
if(left.val != right.val) return false;
确定单层递归的逻辑
此时才进入单层递归的逻辑,单层递归的逻辑就是处理 左右节点都不为空,且数值相同的情况。
- 比较二叉树外侧是否对称:传入的是左节点的左孩子,右节点的右孩子。
- 比较内测是否对称,传入左节点的右孩子,右节点的左孩子。
- 如果左右都对称就返回true ,有一侧不对称就返回false 。
代码如下:
boolean compareOutside = compare(left.left, right.right);
boolean compareInside = compare(left.right, right.left);
return compareOutside && compareInside;
如上代码中,我们可以看出使用的遍历方式,左子树左右中,右子树右左中,所以我把这个遍历顺序也称之为“后序遍历”(尽管不是严格的后序遍历)。
递归整体代码如下:
class Solution {
public boolean isSymmetric(TreeNode root) {
//递归法
return compare(root.left, root.right);
}
private boolean compare(TreeNode left, TreeNode right){
if(left == null && right != null) return false;
if(left != null && right == null) return false;
if(left == null && right == null) return true;
if(left.val != right.val) return false;
//比较外侧
boolean compareOutside = compare(left.left, right.right);
boolean compareInside = compare(left.right, right.left);
return compareOutside && compareInside;
}
}
迭代法
这道题目我们也可以使用迭代法,但要注意,这里的迭代法可不是前中后序的迭代写法,因为本题的本质是判断两个树是否是相互翻转的,其实已经不是所谓二叉树遍历的前中后序的关系了。
这里我们可以使用队列来比较两个树(根节点的左右子树)是否相互翻转,(注意这不是层序遍历)
使用队列
通过队列来判断根节点的左子树和右子树的内侧和外侧是否相等,如动画所示:
如下的条件判断和递归的逻辑是一样的。
使用栈
其实可以发现,这个迭代法,其实是把左右两个子树要比较的元素顺序放进一个容器,然后成对成对的取出来进行比较,那么其实使用栈和队列是一样的。
只要把队列原封不动的改成栈就可以了。
//迭代法
class Solution{
public boolean isSymmetric(TreeNode root){
Deque<TreeNode> stack = new LinkedList<>();
stack.push(root.left);
stack.push(root.right);
while(!stack.isEmpty()){
TreeNode leftNode = stack.pop();
TreeNode rightNode = stack.pop();
if(leftNode == null && rightNode == null) continue; //使用continue,不能直接return true
/**
if(leftNode == null && rightNode != null) return false;
if(leftNode != null && rightNode == null) return false;
if(leftNode.val != rightNode.val) return false;
*/
if(leftNode == null || rightNode == null || leftNode.val != rightNode.val) return false;
stack.push(leftNode.left);
stack.push(rightNode.right);
stack.push(leftNode.right);
stack.push(rightNode.left);
}
return true;
}
}
例:相同的树
//递归法
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
if(p == null || q == null) return false;
if(p.val != q.val){
return false;
}else{
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
}
//迭代法
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
Deque<TreeNode> stack = new LinkedList<>();
stack.push(p);
stack.push(q);
while(!stack.isEmpty()){
TreeNode node1 = stack.pop();
TreeNode node2 = stack.pop();
if(node1 == null && node2 == null) continue;
if(node1 == null || node2 == null ||node1.val != node2.val) return false;
stack.push(node1.left);
stack.push(node2.left);
stack.push(node1.right);
stack.push(node2.right);
}
return true;
}
}
完全二叉树的节点个数
完全二叉树只有两种情况,情况一:就是满二叉树,情况二:最后一层叶子节点没有满。
对于情况一,可以直接用 2^树深度 - 1 来计算,注意这里根节点深度为1。
对于情况二,分别递归左孩子,和右孩子,递归到某一深度一定会有左孩子或者右孩子为满二叉树,然后依然可以按照情况1来计算。
完全二叉树(一)如图:
完全二叉树(二)如图:
可以看出如果整个树不是满二叉树,就递归其左右孩子,直到遇到满二叉树为止,用公式计算这个子树(满二叉树)的节点数量。满二叉树如果层数为n,其节点个数为
利用完全二叉树的性质,本题可以使用更巧妙的写法,我们对当前节点root的左右子树统计高度,左子树高度为leftDepth,右子树高度为rightDepth,此时有两种情况:
- leftDepth==rightDepth:此时右子树和左子树层数相同,那么证明左子树为满二叉树,所以我们当前节点root包含的节点数有2^leftDepth-1+1+右子树个数,即2^leftDepth+右子树个数
- leftDepth!=rightDepth:此时右子树和左子树层数不同,那么此时右子树一定为满二叉树,因为如果右子树不满的话,左右子树的层数相差会大于1不满足满二叉树的定义,此时root包含的节点数有2^rightDepth-1+1+左子树个数,即2^rightDepth+右子树个数
//当作普通的二叉树,层序遍历
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
Queue<TreeNode> queue = new LinkedList<>();
int count = 0;
queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
for(int i = 0; i < len; i++){
TreeNode node = queue.poll();
count++;
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}
return count;
}
}
*/
//完全二叉树
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
if(leftDepth == rightDepth){ // 左子树是满二叉树
return (1 << leftDepth) + countNodes(root.right); //1 << leftDepth 为当前的节点 + 子树的节点的和
}else{// 右子树高度小于左子树,且是满二叉树,左子树不是满二叉树
return (1 << rightDepth) + countNodes(root.left);
}
}
private int getDepth(TreeNode root){
int depth = 0;
while(root != null){
root = root.left;
depth++;
}
return depth;
}
}
平衡二叉树
这里强调一波概念:
- 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数。
- 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数。
但leetcode中强调的深度和高度很明显是按照节点来计算的,如图:
关于根节点的深度究竟是1 还是 0,不同的地方有不一样的标准,leetcode的题目中都是以节点为一度,即根节点深度是1。但维基百科上定义用边为一度,即根节点的深度是0,我们暂时以leetcode为准。
因为求深度可以从上到下去查 所以需要前序遍历(中左右),而高度只能从下到上去查,所以只能后序遍历(左右中)
有的同学一定疑惑,为什么例7.求二叉树的最大深度中求的是二叉树的最大深度,也用的是后序遍历。
那是因为代码的逻辑其实是求的根节点的高度,而根节点的高度就是这棵树的最大深度,所以才可以使用后序遍历。
在例7.求二叉树的最大深度中,如果真正求取二叉树的最大深度,代码应该写成如下:(前序遍历)
//前序遍历
class Solution {
int result;
public int maxDepth(TreeNode root) {
result = 0;
if(root == null) return result;
getDepth(root, 1);
return result;
}
private void getDepth(TreeNode node, int depth){
result = depth > result ? depth : result; //中
if(node.left == null && node.right == null) return;
if(node.left != null){ //左
/**
depth++;//深度+1
getDepth(node.left, depth);
depth--;//回溯, 深度-1
*/
getDepth(node.left, depth + 1);
}
if(node.right != null){
/**
depth++;
getDepth(node.right, depth);
depth--;
*/
getDepth(node.right, depth + 1);
}
return;
}
}
本题思路
递归
此时大家应该明白了既然要求比较高度,必然是要后序遍历。
递归三步曲分析:
明确递归函数的参数和返回值
参数:当前传入节点。
返回值:以当前传入节点为根节点的树的高度。
那么如何标记左右子树是否差值大于1呢?
如果当前传入节点为根节点的二叉树已经不是二叉平衡树了,还返回高度的话就没有意义了。
所以如果已经不是二叉平衡树了,可以返回-1 来标记已经不符合平衡树的规则了。
代码如下:
// -1 表示已经不是平衡二叉树了,否则返回值是以该节点为根节点树的高度
int getHeight(TreeNode node)
明确终止条件
递归的过程中依然是遇到空节点了为终止,返回0,表示当前节点为根节点的树高度为0
代码如下:
if (node == NULL) {
return 0;
}
明确单层递归的逻辑
如何判断以当前传入节点为根节点的二叉树是否是平衡二叉树呢?当然是其左子树高度和其右子树高度的差值。
分别求出其左右子树的高度,然后如果差值小于等于1,则返回当前二叉树的高度,否则则返回-1,表示已经不是二叉平衡树了。
代码如下:
int leftHight = getHight(node.left);
if(leftHight == -1) return -1;
int rightHight = getHight(node.right);
if(rightHight == -1) return -1;
if(Math.abs(leftHight - rightHight) > 1) return -1;
return Math.max(leftHight, rightHight) + 1;
此时递归的函数就已经写出来了,这个递归的函数传入节点指针,返回以该节点为根节点的二叉树的高度,如果不是二叉平衡树,则返回-1。
总体代码如下:
class Solution {
public boolean isBalanced(TreeNode root) {
return getHight(root) != -1;
}
private int getHight(TreeNode node){
if(node == null) return 0;
int leftHight = getHight(node.left);
if(leftHight == -1) return -1;
int rightHight = getHight(node.right);
if(rightHight == -1) return -1;
if(Math.abs(leftHight - rightHight) > 1) return -1; //Math.abs求绝对值
return Math.max(leftHight, rightHight) + 1;
}
}
迭代
在求二叉树的最大深度中我们可以使用层序遍历来求深度,但是就不能直接用层序遍历来求高度了,这就体现出求高度和求深度的不同。
本题的迭代方式可以先定义一个函数,专门用来求高度。
这个函数通过栈模拟的后序遍历找每一个节点的高度(其实是通过求传入节点为根节点的最大深度来求的高度)
代码如下:
class Solution {
public int maxDepth(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
if(root != null) stack.push(root);
int maxDepth = 0;
int result = 0;
while(!stack.isEmpty()){
TreeNode node = stack.peek();
if(node != null){
stack.pop();
stack.push(node);
stack.push(null);
maxDepth++;
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}else{
stack.pop();
node = stack.peek();
stack.pop();
maxDepth--;
}
result = result > maxDepth ? result : maxDepth;
}
return result;
}
}
然后再用栈来模拟后序遍历,遍历每一个节点的时候,再去判断左右孩子的高度是否符合,代码如下:
public boolean isBalanced(TreeNode root) {
Deque<TreeNode> stack1 = new LinkedList<>();
if(root == null) return true;
stack1.push(root);
while(!stack1.isEmpty()){
TreeNode node = stack1.peek();
stack1.poll();
if(Math.abs(getHight(node.left) - getHight(node.right)) > 1) return false;
if(node.right != null) stack1.push(node.right);
if(node.left != null) stack1.push(node.left);
}
return true;
}
整体代码如下:
class Solution {
public boolean isBalanced(TreeNode root) {
Deque<TreeNode> stack1 = new LinkedList<>();
if(root == null) return true;
stack1.push(root);
while(!stack1.isEmpty()){
TreeNode node = stack1.peek();
stack1.poll();
if(Math.abs(getHight(node.left) - getHight(node.right)) > 1) return false;
if(node.right != null) stack1.push(node.right);
if(node.left != null) stack1.push(node.left);
}
return true;
}
//求高度方法一:层序遍历求高度
public int getHight(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
if(root != null) queue.offer(root);
int maxDepth = 0;
while(!queue.isEmpty()){
int len = queue.size();
for(int i = 0; i < len; i++){
TreeNode node = queue.poll();
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
maxDepth++;
}
return maxDepth;
}
//求高度方法二:后序遍历求高度
public int getHight(TreeNode root) {
Deque<TreeNode> stack = new LinkedList<>();
if(root != null) stack.push(root);
int maxDepth = 0;
int result = 0;
while(!stack.isEmpty()){
TreeNode node = stack.peek();
if(node != null){
stack.pop();
stack.push(node);
stack.push(null);
maxDepth++;
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}else{
stack.pop();
node = stack.peek();
stack.pop();
maxDepth--;
}
result = result > maxDepth ? result : maxDepth;
}
return result;
}
}
当然此题用迭代法,其实效率很低,因为没有很好的模拟回溯的过程,所以迭代法有很多重复的计算。
虽然理论上所有的递归都可以用迭代来实现,但是有的场景难度可能比较大。
例如:都知道回溯法其实就是递归,但是很少人用迭代的方式去实现回溯算法!
因为对于回溯算法已经是非常复杂的递归了,如果在用迭代的话,就是自己给自己找麻烦,效率也并不一定高。
通过本题可以了解求二叉树深度 和 二叉树高度的差异,求深度适合用前序遍历,而求高度适合用后序遍历。
构造二叉树
从中序与后序遍历序列构造二叉树
首先回忆一下如何根据两个顺序构造一个唯一的二叉树,相信理论知识大家应该都清楚,就是以 后序数组的最后一个元素为切割点,先切中序数组,根据中序数组,反过来在切后序数组。一层一层切下去,每次后序数组最后一个元素就是节点元素。
如果让我们肉眼看两个序列,画一棵二叉树的话,应该分分钟都可以画出来。
流程如图:
那么代码应该怎么写呢?
说到一层一层切割,就应该想到了递归。
来看一下一共分几步:
-
第一步:如果数组大小为零的话,说明是空节点了。
-
第二步:如果不为空,那么取后序数组最后一个元素作为节点元素。
-
第三步:找到后序数组最后一个元素在中序数组的位置,作为切割点
-
第四步:切割中序数组,切成中序左数组和中序右数组 (顺序别搞反了,一定是先切中序数组)
-
第五步:切割后序数组,切成后序左数组和后序右数组
-
第六步:递归处理左区间和右区间
难点大家应该发现了,就是如何切割,以及边界值找不好很容易乱套。
此时应该注意确定切割的标准,是左闭右开,还有左开右闭,还是左闭右闭,这个就是不变量,要在递归中保持这个不变量。
在切割的过程中会产生四个区间,把握不好不变量的话,一会左闭右开,一会左闭右闭,必然乱套!
首先要切割中序数组,为什么先切割中序数组呢?
切割点在后序数组的最后一个元素,就是用这个元素来切割中序数组的,所以必要先切割中序数组。
中序数组相对比较好切,找到切割点(后序数组的最后一个元素)在中序数组的位置,然后切割,代码中我坚持左闭右开的原则
接下来就要切割后序数组了。
首先后序数组的最后一个元素指定不能要了,这是切割点 也是 当前二叉树中间节点的元素,已经用了。后序数组的切割点怎么找?
后序数组没有明确的切割元素来进行左右切割,不像中序数组有明确的切割点,切割点左右分开就可以了。
此时有一个很重的点,就是中序数组大小一定是和后序数组的大小相同的(这是必然)。
中序数组我们都切成了左中序数组和右中序数组了,那么后序数组就可以按照左中序数组的大小来切割,切成左后序数组和右后序数组。
此时,中序数组切成了左中序数组和右中序数组,后序数组切割成左后序数组和右后序数组。
接下来可以递归了,完整代码如下:
class Solution {
Map<Integer, Integer> map = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
for (int i = 0; i < inorder.length; i++) { // 用map保存中序序列的数值对应位置
map.put(inorder[i], i);
}
return findNode(inorder, 0, inorder.length, postorder,0, postorder.length); // 前闭后开
}
public TreeNode findNode(int[] inorder, int inBegin, int inEnd, int[] postorder, int postBegin, int postEnd) {
// 参数里的范围都是前闭后开
if (inBegin >= inEnd || postBegin >= postEnd) { // 不满足左闭右开,说明没有元素,返回空树
return null;
}
int rootIndex = map.get(postorder[postEnd - 1]); // 找到后序遍历的最后一个元素在中序遍历中的位置
TreeNode root = new TreeNode(inorder[rootIndex]); // 构造结点
int lenOfLeft = rootIndex - inBegin; // 保存中序左子树个数,用来确定后序数列的个数
root.left = findNode(inorder, inBegin, rootIndex, postorder, postBegin, postBegin + lenOfLeft);
root.right = findNode(inorder, rootIndex + 1, inEnd, postorder, postBegin + lenOfLeft, postEnd - 1);
return root;
}
}
从前序与中序遍历序列构造二叉树
class Solution {
Map<Integer, Integer> map = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
for(int i = 0; i < inorder.length; i++){
map.put(inorder[i], i);
}
return findNode(inorder, 0, inorder.length, preorder, 0, preorder.length);
}
public TreeNode findNode(int[] inorder, int inBegin, int inEnd, int[] preorder, int preBegin, int preEnd){
if(inBegin >= inEnd || preBegin >= preEnd) return null;
int rootIndex = map.get(preorder[preBegin]);
TreeNode root = new TreeNode(inorder[rootIndex]);
int leftOfLen = rootIndex - inBegin;
root.left = findNode(inorder, inBegin, rootIndex, preorder, preBegin + 1, preBegin + leftOfLen + 1);
root.right = findNode(inorder, rootIndex + 1, inEnd, preorder, preBegin + leftOfLen + 1, preEnd);
return root;
}
}
思考
前序和中序可以唯一确定一棵二叉树。
后序和中序可以唯一确定一棵二叉树。
那么前序和后序可不可以唯一确定一棵二叉树呢?
前序和后序不能唯一确定一棵二叉树!,因为没有中序遍历无法确定左右部分,也就是无法分割。
举一个例子:
tree1 的前序遍历是[1 2 3], 后序遍历是[3 2 1]。
tree2 的前序遍历是[1 2 3], 后序遍历是[3 2 1]。
那么tree1 和 tree2 的前序和后序完全相同,这是一棵树么,很明显是两棵树!
所以前序和后序不能唯一确定一棵二叉树!
最大二叉树
注意类似用数组构造二叉树的题目,每次分隔尽量不要定义新的数组,而是通过下标索引直接在原数组上操作,这样可以节约时间和空间上的开销。
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return binaryTree(nums, 0, nums.length); //左闭右开区间
}
public TreeNode binaryTree(int[] nums, int leftIndex, int rightIndex){
if(rightIndex - leftIndex < 1) return null;//说明没有元素了
if(rightIndex - leftIndex == 1) return new TreeNode(nums[leftIndex]);//只有一个元素了,为叶子结点
int maxIndex = leftIndex; //定义最大值所在索引
int maxVal = nums[leftIndex]; //定义最大值
for(int i = leftIndex + 1; i < rightIndex; i++){
if(nums[i] > maxVal){
maxIndex = i;
maxVal = nums[i];
}
}
TreeNode root = new TreeNode(maxVal);
root.left = binaryTree(nums, leftIndex, maxIndex);
root.right = binaryTree(nums, maxIndex + 1, rightIndex);
return root;
}
}
有序数组转换为二叉搜索树
题目中说要转换为一棵高度平衡二叉搜索树。这和转换为一棵普通二叉搜索树有什么差别呢?
其实这里不用强调平衡二叉搜索树,数组构造二叉树,构成平衡树是自然而然的事情,因为大家默认都是从数组中间位置取值作为节点元素,一般不会随机取,所以想构成不平衡的二叉树是自找麻烦。本质就是寻找分割点,分割点作为当前节点,然后递归左区间和右区间。
分割点就是数组中间位置的节点。
那么为问题来了,如果数组长度为偶数,中间节点有两个,取哪一个?
取哪一个都可以,只不过构成了不同的平衡二叉搜索树。
例如:输入:[-10,-3,0,5,9]
如下两棵树,都是这个数组的平衡二叉搜索树:
如果要分割的数组长度为偶数的时候,中间元素为两个,是取左边元素 就是树1,取右边元素就是树2。这也是题目中强调答案不是唯一的原因。
递归
在构造二叉树的时候尽量不要重新定义左右区间数组,而是用下标来操作原数组。
首先取数组中间元素的位置,不难写出int mid = (left + right) / 2;
,这么写其实有一个问题,就是数值越界,例如left和right都是最大int,这么操作就越界了,在二分法中尤其需要注意!
所以可以这么写:int mid = left + ((right - left) >> 1);
但本题leetcode的测试数据并不会越界,所以怎么写都可以。但需要有这个意识!
这里int mid = left + ((right - left) / 2);
的写法相当于是如果数组长度为偶数,中间位置有两个元素,取靠左边的。
- 递归整体代码如下:
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return toBST(nums, 0, nums.length); //左闭右开区间
}
public TreeNode toBST(int[] nums, int leftIndex, int rightIndex){
if(leftIndex >= rightIndex) return null;
if(rightIndex - leftIndex == 1){
return new TreeNode(nums[leftIndex]); //叶子结点
}
int midIndex = leftIndex + ((rightIndex - leftIndex) >> 1);//防止越界溢出
TreeNode root = new TreeNode(nums[midIndex]);
root.left = toBST(nums, leftIndex, midIndex);
root.right = toBST(nums, midIndex + 1, rightIndex);
return root;
}
}
迭代法
迭代法可以通过三个队列来模拟,一个队列放遍历的节点,一个队列放左区间下标,一个队列放右区间下标。模拟的就是不断分割的过程,代码如下:
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums.length == 0) return null;
//根节点初始化
TreeNode root = new TreeNode(-1);
Queue<TreeNode> nodeQueue = new LinkedList<>();
Queue<Integer> leftQueue = new LinkedList<>();
Queue<Integer> rightQueue = new LinkedList<>();
// 根节点入队列
nodeQueue.offer(root);
// 0为左区间下标初始位置
leftQueue.offer(0);
// nums.size() - 1为右区间下标初始位置
rightQueue.offer(nums.length - 1);
while (!nodeQueue.isEmpty()) {
TreeNode currNode = nodeQueue.poll();
int left = leftQueue.poll();
int right = rightQueue.poll();
int mid = left + ((right - left) >> 1);
// 将mid对应的元素给中间节点
currNode.val = nums[mid];
// 处理左区间
if (left <= mid - 1) {
currNode.left = new TreeNode(-1);
nodeQueue.offer(currNode.left);
leftQueue.offer(left);
rightQueue.offer(mid - 1);
}
// 处理右区间
if (right >= mid + 1) {
currNode.right = new TreeNode(-1);
nodeQueue.offer(currNode.right);
leftQueue.offer(mid + 1);
rightQueue.offer(right);
}
}
return root;
}
}