Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Implemented Morris Traversal v2#1808

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
aniket866 wants to merge2 commits intoTheAlgorithms:master
base:master
Choose a base branch
Loading
fromaniket866:MorrisTraversal-v2
Open
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletionsTrees/MorrisTraversal.js
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
export class Node {
constructor(data) {
this.data = data
this.left = null
this.right = null
}
}

export class BinaryTree {
constructor() {
this.root = null
}

morrisTraversal() {
const traversal = []
let current = this.root

while (current !== null) {
if (current.left === null) {
traversal.push(current.data)
current = current.right
} else {
let predecessor = current.left
while (predecessor.right !== null && predecessor.right !== current) {
predecessor = predecessor.right
}

if (predecessor.right === null) {
predecessor.right = current
current = current.left
} else {
predecessor.right = null
traversal.push(current.data)
current = current.right
}
}
}

return traversal
}
}
23 changes: 23 additions & 0 deletionsTrees/test/MorrisTraversal.test.js
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
import { BinaryTree, Node } from '../Trees/MorrisTraversal.js'

describe('Morris Inorder Tree Traversal', () => {
const binaryTree = new BinaryTree()

const root = new Node(7)
root.left = new Node(5)
root.right = new Node(8)
root.left.left = new Node(3)
root.left.right = new Node(6)
root.left.right.right = new Node(9)
binaryTree.root = root

it('Binary tree - Empty case', () => {
const emptyTree = new BinaryTree()
expect(emptyTree.morrisTraversal()).toStrictEqual([])
})

it('Binary tree - Morris inorder traversal', () => {
const traversal = binaryTree.morrisTraversal()
expect(traversal).toStrictEqual([3, 5, 6, 9, 7, 8])
})
})
Loading

[8]ページ先頭

©2009-2025 Movatter.jp