【剑指offer】5.二叉树的镜像和打印

栏目: 数据库 · 发布时间: 7年前

内容简介:基本结构:二叉树的前序、中序、后序遍历的定义:前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;

二叉树简介

基本结构:

function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
}

二叉树的前序、中序、后序遍历的定义:

前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;

中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;

后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。

题目1 二叉树的镜像

1.1 题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。

输入描述:
二叉树的镜像定义:源二叉树 
            8
           /  \
          6   10
         / \  / \
        5  7 9 11
        镜像二叉树
            8
           /  \
          10   6
         / \  / \
        11 9 7  5

1.2 解题思路

递归交换二叉树两棵字树的位置。

1.3 代码

function Mirror(root)
{
    if(root){
        const temp = root.right;
        root.right = root.left;
        root.left = temp;
        Mirror(root.right);
        Mirror(root.left);
    }
}

题目2 从上往下打印二叉树

2.1 题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

2.2 解题思路

1.借助队列先进先出的数据结构

2.让二叉树每层依次进入队列

3.依次打印队列中的值

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;
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Computers and Intractability

Computers and Intractability

M R Garey、D S Johnson / W. H. Freeman / 1979-4-26 / GBP 53.99

This book's introduction features a humorous story of a man with a line of people behind him, who explains to his boss, "I can't find an efficient algorithm, but neither can all these famous people." ......一起来看看 《Computers and Intractability》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

在线进制转换器
在线进制转换器

各进制数互转换器

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具