6.二叉树——1.层次建树与遍历

2024-03-19 07:20
文章标签 二叉树 遍历 层次 建树

本文主要是介绍6.二叉树——1.层次建树与遍历,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

层次建树的逻辑

  1. 创建根节点 TreeNode * root=NULL
  2. 创建一个队列,用于保存将要插入的位置(先进先出)
  3. 读取字符:
    • 如果不是#,表明是非空结点,创建一个TreeNode对象,把该对象的左右孩子入队;然后判断root是否空
      • 若空,直接插入,让root指向新的TreeNode对象
      • 非空,访问队列找到本次插入的位置,插入
    • 若是#,访问队列,找到本次插入的位置,置为空指针,然后出队

代码

#include <cstdio>
#include <string>
#include <map>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
using namespace std;struct TreeNode{int data;TreeNode * leftChild;TreeNode * rightChild;
};
struct QueueNode{TreeNode *parent;bool isLeftIn;
};//插入操作会修改root(main函数中申请)的指向,所以需要使用引用
void insertTreeNode(TreeNode *&root,queue<QueueNode*> &myQueue,char data){if (data!='#'){//创建二叉树结点,在堆上创建,因为是在被调函数内创建TreeNode *newNode = new TreeNode;(*newNode).data = data;//*运算的优先级没有.高//或者:(*p).member等价于p->member//入队QueueNode* que = new QueueNode;que->parent = newNode;que->isLeftIn = false;myQueue.push(que);//插入操作if (root==NULL){//插入的第一个结点root = newNode;} else{//插入的不是根//parent用于定位插入结点的父亲位置QueueNode * Qparent = myQueue.front();if (Qparent->isLeftIn){Qparent->parent->leftChild = newNode;Qparent->isLeftIn= true;} else{Qparent->parent->rightChild = newNode;myQueue.pop();delete Qparent;//出队后,原来的队首元素没有用了}}} else{//是#,表明要插入一个空节点if (root!=NULL){//队列不为空QueueNode * Qparent = myQueue.front();if (Qparent->isLeftIn== false){Qparent->parent->leftChild=NULL;Qparent->isLeftIn= true;} else{Qparent->parent->rightChild = NULL;myQueue.pop();delete Qparent;//出队后,原来的队首元素没有用了}}}
}
int main() {TreeNode *root=NULL ;//根节点char list[] = "abc##de#g##f###";queue<QueueNode*> myQueue;//队列每个元素存储了新节点的父亲位置,以及是否插入过左孩子for (int i = 0; list[i]!='\0'; ++i) {insertTreeNode(root,);}return 0;
}

二叉树遍历

层次遍历:广度优先(使用队列)

  • 访问起点,把起点的邻居(左右孩子)加入队列
  • 按照队列出队顺序,把访问结点的邻居(左右孩子)加入队列

代码

void levelOrder(TreeNode *root){queue<TreeNode*> pos;//存储将要访问的结点地址pos.push(root);while(pos.empty()== false){TreeNode *pCur = pos.front();//找到队头pos.pop();//出队//访问队头printf("%c",pCur->data);//把队首的邻居加入队列if (pCur->leftChild!=NULL){pos.push(pCur->leftChild);}if (pCur->rightChild!=NULL){pos.push(pCur->rightChild);}}printf("\n");
}

递归遍历

先序遍历

void preOrder(TreeNode* root){if (root==NULL){return;}printf("%c",root->data);preOrder(root->leftChild);preOrder(root->rightChild);
}

中序遍历

void preOrder(TreeNode* root){if (root==NULL){return;}preOrder(root->leftChild);printf("%c",root->data);preOrder(root->rightChild);
}

后序遍历

void preOrder(TreeNode* root){if (root==NULL){return;}preOrder(root->leftChild);preOrder(root->rightChild);printf("%c",root->data);
}

本文代码全家福

#include <cstdio>
#include <string>
#include <map>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
using namespace std;struct TreeNode{char data;TreeNode * leftChild;TreeNode * rightChild;
};
struct QueueNode{TreeNode *parent;bool isLeftIn;
};//插入操作会修改root(main函数中申请)的指向,所以需要使用引用
void insertTreeNode(TreeNode *&root,queue<QueueNode*> &myQueue,char data){if (data!='#'){//创建二叉树结点,在堆上创建,因为是在被调函数内创建TreeNode *newNode = new TreeNode;(*newNode).data = data;//*运算的优先级没有.高//或者:(*p).member等价于p->member//入队QueueNode* que = new QueueNode;que->parent = newNode;que->isLeftIn = false;myQueue.push(que);//插入操作if (root==NULL){//插入的第一个结点root = newNode;} else{//插入的不是根//parent用于定位插入结点的父亲位置QueueNode * Qparent = myQueue.front();if (!Qparent->isLeftIn){Qparent->parent->leftChild = newNode;Qparent->isLeftIn= true;} else{Qparent->parent->rightChild = newNode;myQueue.pop();delete Qparent;//出队后,原来的队首元素没有用了}}} else{//是#,表明要插入一个空节点if (root!=NULL){//队列不为空QueueNode * Qparent = myQueue.front();if (Qparent->isLeftIn== false){Qparent->parent->leftChild=NULL;Qparent->isLeftIn= true;} else{Qparent->parent->rightChild = NULL;myQueue.pop();delete Qparent;//出队后,原来的队首元素没有用了}}}
}
void levelOrder(TreeNode *root){queue<TreeNode*> pos;//存储将要访问的结点地址pos.push(root);while(pos.empty()== false){TreeNode *pCur = pos.front();//找到队头pos.pop();//出队//访问队头printf("%c",pCur->data);//把队首的邻居加入队列if (pCur->leftChild!=NULL){pos.push(pCur->leftChild);}if (pCur->rightChild!=NULL){pos.push(pCur->rightChild);}}printf("\n");
}
void preOrder(TreeNode* root){if (root==NULL){return;}printf("%c",root->data);preOrder(root->leftChild);preOrder(root->rightChild);
}
void midOrder(TreeNode* root){if (root==NULL){return;}preOrder(root->leftChild);printf("%c",root->data);preOrder(root->rightChild);
}
void aftOrder(TreeNode* root){if (root==NULL){return;}preOrder(root->leftChild);preOrder(root->rightChild);printf("%c",root->data);
}
int main() {TreeNode *root=NULL ;//根节点char list[] = "abc##de#g##f###";queue<QueueNode*> myQueue;//队列每个元素存储了新节点的父亲位置,以及是否插入过左孩子for (int i = 0; list[i]!='\0'; ++i) {insertTreeNode(root,myQueue,list[i]);}levelOrder(root);preOrder(root);printf("\n");midOrder(root);printf("\n");aftOrder(root);return 0;
}

这篇关于6.二叉树——1.层次建树与遍历的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/825211

相关文章

C++中使用vector存储并遍历数据的基本步骤

《C++中使用vector存储并遍历数据的基本步骤》C++标准模板库(STL)提供了多种容器类型,包括顺序容器、关联容器、无序关联容器和容器适配器,每种容器都有其特定的用途和特性,:本文主要介绍C... 目录(1)容器及简要描述‌php顺序容器‌‌关联容器‌‌无序关联容器‌(基于哈希表):‌容器适配器‌:(

leetcode105 从前序与中序遍历序列构造二叉树

根据一棵树的前序遍历与中序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。 例如,给出 前序遍历 preorder = [3,9,20,15,7]中序遍历 inorder = [9,3,15,20,7] 返回如下的二叉树: 3/ \9 20/ \15 7   class Solution {public TreeNode buildTree(int[] pr

PHP实现二叉树遍历(非递归方式,栈模拟实现)

二叉树定义是这样的:一棵非空的二叉树由根结点及左、右子树这三个基本部分组成,根据节点的访问位置不同有三种遍历方式: ① NLR:前序遍历(PreorderTraversal亦称(先序遍历)) ——访问结点的操作发生在遍历其左右子树之前。 ② LNR:中序遍历(InorderTraversal) ——访问结点的操作发生在遍历其左右子树之中(间)。 ③ LRN:后序遍历(PostorderT

react笔记 8-17 属性绑定 class绑定 引入图片 循环遍历

1、绑定属性 constructor(){super()this.state={name:"张三",title:'我是一个title'}}render() {return (<div><div>aaaaaaa{this.state.name}<div title={this.state.title}>我是一个title</div></div></div>)} 绑定属性直接使用花括号{}   注

MATLAB层次聚类分析法

转自:http://blog.163.com/lxg_1123@126/blog/static/74841406201022774051963/ 层次聚类是基于距离的聚类方法,MATLAB中通过pdist、linkage、dendrogram、cluster等函数来完成。层次聚类的过程可以分这么几步: (1) 确定对象(实际上就是数据集中的每个数据点)之间的相似性,实际上就是定义一个表征

在二叉树中找到两个节点的最近公共祖先(基于Java)

如题  题解 public int lowestCommonAncestor(TreeNode root, int o1, int o2) {//记录遍历到的每个节点的父节点。Map<Integer, Integer> parent = new HashMap<>();Queue<TreeNode> queue = new LinkedList<>();parent.put(roo

数据结构--二叉树(C语言实现,超详细!!!)

文章目录 二叉树的概念代码实现二叉树的定义创建一棵树并初始化组装二叉树前序遍历中序遍历后序遍历计算树的结点个数求二叉树第K层的结点个数求二叉树高度查找X所在的结点查找指定节点在不在完整代码 二叉树的概念 二叉树(Binary Tree)是数据结构中一种非常重要的树形结构,它的特点是每个节点最多有两个子节点,通常称为左子节点和右子节点。这种结构使得二叉树在数据存储和查找等方面具

hashmap的存值,各种遍历方法

package com.jefflee;import java.util.HashMap;import java.util.Iterator;import java.util.Map;public class HashmapTest {// 遍历Hashmap的四种方法public static void main(String[] args) {//hashmap可以存一个null,把

Knight Moves -uva 简单的BFS遍历

昨天刚学了BFS的遍历,在uva上找了个题敲了出来,感觉还不错,最近敲代码挺有手感的,希望这种状态保持下去 #include<iostream>#include<stdio.h>#include<stdlib.h>#include<string.h>#define MAX_SIZE 10 + 5#define LEN 100 + 10using namespace std;in

笔试强训,[NOIP2002普及组]过河卒牛客.游游的水果大礼包牛客.买卖股票的最好时机(二)二叉树非递归前序遍历

目录 [NOIP2002普及组]过河卒 牛客.游游的水果大礼包 牛客.买卖股票的最好时机(二) 二叉树非递归前序遍历 [NOIP2002普及组]过河卒 题里面给的提示很有用,那个马的关系,后面就注意,dp需要作为long的类型。 import java.util.Scanner;// 注意类名必须为 Main, 不要有任何 package xxx 信息publ