多叉树的先序遍历、后序遍历、层次遍历

2023-12-03 23:32

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

package com;import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;/*** @author liushihao <liushihao@kuaishou.com>* Created on 2021/4/12 4:38 下午*/
public class TreeTest {public static void main(String[] args) {/*       12   3   45 6   7   8 9*/NaryTreeNode root = new NaryTreeNode(1);root.addChildNode(new NaryTreeNode(2));root.addChildNode(new NaryTreeNode(3));root.addChildNode(new NaryTreeNode(4));List<NaryTreeNode> childList = root.getChildren();childList.get(0).addChildNode(new NaryTreeNode(5));childList.get(0).addChildNode(new NaryTreeNode(6));childList.get(1).addChildNode(new NaryTreeNode(7));childList.get(2).addChildNode(new NaryTreeNode(8));childList.get(2).addChildNode(new NaryTreeNode(9));for (int i : preOrder(root)) {System.out.print(i + "  ");}System.out.println();for (int i : postOrder(root)) {System.out.print(i + "  ");}System.out.println();for (List<Integer> i : levelOrder(root)) {for (int a : i) {System.out.print(a + "  ");}System.out.println();}}/*** 先序遍历:根左右* 利用栈模拟递归调用* 将根结点压入栈中,当栈不空时执行:* 弹出栈中结点,将其放入结果队列中* 将该结点的孩子按照倒序依次放入栈中*/public static List<Integer> preOrder(NaryTreeNode root) {Deque<NaryTreeNode> stack = new LinkedList<>();List<Integer> pre = new LinkedList<>();if (root == null) return pre;stack.add(root);while (!stack.isEmpty()) {NaryTreeNode node = stack.pop();pre.add(node.getVal());Deque<NaryTreeNode> reChildren = new LinkedList<>(node.getChildren());while (!reChildren.isEmpty()) {stack.push(reChildren.pop());}}return pre;}/*** 后序遍历:左右根* 利用栈模拟递归调用* 将根结点压入栈中,当栈不空时执行:* 弹出栈中结点,将其头插放入结果队列中* 将该结点的孩子依次放入栈中* * * 其实后序遍历就是先序遍历的逆序列* 先序遍历:先遍历children再遍历root* 后序遍历:先遍历root再遍历children*/public static List<Integer> postOrder(NaryTreeNode root) {Deque<NaryTreeNode> stack = new LinkedList<>();LinkedList<Integer> post = new LinkedList<>();if (root == null) return post;stack.add(root);while (!stack.isEmpty()) {NaryTreeNode node = stack.pop();// LinkedList的add方法是尾插法post.addFirst(node.getVal());for (NaryTreeNode child : node.getChildren()) {stack.push(child);}}return post;}/*** 层次遍历:* 利用队列模拟递归调用* 将根结点压入队中,当队不空时执行:* 获取当前队列长度,当迭代次数小于当前队列长度时:* 弹出当前队头结点,将其放入当前层的结果队列中* 将该结点的孩子依次放入队列中* 将当前层的结果队列放入结果队列中*/public static List<List<Integer>> levelOrder(NaryTreeNode root) {List<List<Integer>> result = new ArrayList<>();if (root == null) return result;Queue<NaryTreeNode> queue = new LinkedList<>();queue.add(root);while (!queue.isEmpty()) {List<Integer> level = new ArrayList<>();int size = queue.size();for (int i = 0; i < size; i++) {NaryTreeNode node = queue.poll();level.add(node.getVal());queue.addAll(node.getChildren());}result.add(level);}return result;}
}class NaryTreeNode {private int val;private List<NaryTreeNode> children;public NaryTreeNode(int val) {this.val = val;children = new ArrayList<NaryTreeNode>();}public NaryTreeNode(int val, List<NaryTreeNode> children) {this.val = val;if (children != null) this.children = children;else this.children = new ArrayList<NaryTreeNode>();}public int getVal() {return val;}public List<NaryTreeNode> getChildren() {return children;}public boolean isLeaf() {return children.isEmpty();}public boolean addChildNode(NaryTreeNode node) {children.add(node);return true;}
}

这篇关于多叉树的先序遍历、后序遍历、层次遍历的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

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) 确定对象(实际上就是数据集中的每个数据点)之间的相似性,实际上就是定义一个表征

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

二叉树的层次遍历(10道)

(写给未来遗忘的自己) 102.二叉数的层序遍历(从上到下) 题目: 代码: class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> result; queue<TreeNode*> node; if (root == nullptr) {

关于双指针遍历

今晚跟一个朋友突然问我,你懂双指针遍历吗?并叫我敲出代码。当时自己愣住了,但是还是写出来了,第一个版本是: #include <iostream> using namespace std; int main(int argc, char** argv, char** arge) { cout<<"输出参数个数:"<<argc<<endl; cout<<"输出字符串数组:"<<endl; f

【ML--13】聚类--层次聚类

一、基本概念 层次聚类不需要指定聚类的数目,首先它是将数据中的每个实例看作一个类,然后将最相似的两个类合并,该过程迭代计算只到剩下一个类为止,类由两个子类构成,每个子类又由更小的两个子类构成。 层次聚类方法对给定的数据集进行层次的分解,直到某种条件满足或者达到最大迭代次数。具体又可分为: 凝聚的层次聚类(AGNES算法):一种自底向上的策略,首先将每个对象作为一个簇,然后合并这些原子簇为越来