How to resolve the algorithm Tree traversal step by step in the Ceylon programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Tree traversal step by step in the Ceylon programming language

Table of Contents

Problem Statement

Implement a binary tree where each node carries an integer,   and implement:

Use those traversals to output the following tree: The correct output should look like this:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Tree traversal step by step in the Ceylon programming language

Source code in the ceylon programming language

import ceylon.collection {
	ArrayList
}

shared void run() {

	class Node(label, left = null, right = null) {
		shared Integer label;
		shared Node? left;
		shared Node? right;
		string => label.string;
	}
	
	void preorder(Node node) {
		process.write(node.string + " ");
		if(exists left = node.left) {
			preorder(left);
		}
		if(exists right = node.right) {
			preorder(right);
		}
	}
	
	void inorder(Node node) {
		if(exists left = node.left) {
			inorder(left);
		}
		process.write(node.string + " ");
		if(exists right = node.right) {
			inorder(right);
		}
	}
	
	void postorder(Node node) {
		if(exists left = node.left) {
			postorder(left);
		}
		if(exists right = node.right) {
			postorder(right);
		}
		process.write(node.string + " ");
	}
	
	void levelOrder(Node node) {
		value nodes = ArrayList {node};
		while(exists current = nodes.accept()) {
			process.write(current.string + " ");
			if(exists left = current.left) {
				nodes.offer(left);
			}
			if(exists right = current.right) {
				nodes.offer(right);
			}
		}
	}

	value tree = Node {
		label = 1;
		left = Node {
			label = 2;
			left = Node {
				label = 4;
				left = Node {
					label = 7;
				};
			};
			right = Node {
				label = 5;
			};
		};
		right = Node {
			label = 3;
			left = Node {
				label = 6;
				left = Node {
					label = 8;
				};
				right = Node {
					label = 9;
				};
			};
		};
	};
	
	process.write("preorder:   ");
	preorder(tree);
	print("");
	process.write("inorder:    ");
	inorder(tree);
	print("");
	process.write("postorder:  ");
	postorder(tree);
	print("");
	process.write("levelorder: ");
	levelOrder(tree);
	print("");
}


  

You may also check:How to resolve the algorithm Copy a string step by step in the REXX programming language
You may also check:How to resolve the algorithm Return multiple values step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Matrix chain multiplication step by step in the C programming language
You may also check:How to resolve the algorithm Program name step by step in the LLVM programming language
You may also check:How to resolve the algorithm FizzBuzz step by step in the Pop11 programming language