导读:
分类:技术干货
题目:二叉树的遍历和重建
一起重温《剑指offer》,再也不怕手写算法啦!
基本结构:
function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
}
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
递归交换二叉树两棵字树的位置。
function Mirror(root)
{
if(root){
const temp = root.right;
root.right = root.left;
root.left = temp;
Mirror(root.right);
Mirror(root.left);
}
}
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
1.借助队列先进先出的数据结构
2.让二叉树每层依次进入队列
3.依次打印队列中的值
function PrintFromTopToBottom(root) {
const queue = [];
const print = [];
if(root != null){
queue.push(root);
}
while (queue.length > 0) {
const current = queue.shift();
print.push(current.val);
if (current.left) {
queue.push(current.left);
}
if (current.right) {
queue.push(current.right);
}
}
return print;
}