二叉树

二叉排序树

class Node {
	constructor(value) {
		this.value = value
		this.left = null
		this.right = null
	}
}

class Tree {
	constructor() {
		this.root = null
		this.travelResult = []
	}
	insertByFather(father, node) {
		if (father.value > node.value) {
			if (father.left === null) {
				father.left = node
			} else {
				this.insertByFather(father.left, node)
			}
		} else {
			if (father.right === null) {
				father.right = node
			} else {
				this.insertByFather(father.right, node)
			}
		}
	}
	insert(value) {
		const node = new Node(value)
		if (this.root === null) {
			this.root = node
		} else {
			this.insertByFather(this.root, node)
		}
	}
// 什么续遍历就是将根节点放在哪个位置
// 前序就是将根节点放第一位,以此类推 preTravel(node) { if (node) { this.travelResult.push(node.value) this.preTravel(node.left) this.preTravel(node.right) } } _preTravel(root) { if (root) { const stack = [] stack.push(root) while (stack.length > 0) { const node = stack.pop() this.travelResult.push(node.value) if (node.right) { stack.push(node.right) } if (node.left) { stack.push(node.left) } } } } midTravel(node) { if (node) { this.midTravel(node.left) this.travelResult.push(node.value) this.midTravel(node.right) } } _midTravel(root) { if (root) { const stack = [] let node = root while(node || stack.length > 0) { while(node) { stack.push(node) node = node.left } node = stack.pop() this.travelResult.push(node.value) node = node.right } } } lastTravel(node) { if (node) { this.lastTravel(node.left) this.lastTravel(node.right) this.travelResult.push(node.value) } } _lastTravel(root) { if (root) { const stack = [] stack.push(root) while (stack.length > 0) { const node = stack.pop() this.travelResult.push(node.value)
        if (node.left) {
          stack.push(node.left)
        } if (node.right) { stack.push(node.right) } } } this.travelResult = this.travelResult.reverse() } }

完全二叉树

class Node {
	constructor(value) {
		this.value = value
		this.left = null
		this.right = null
	}
}

class Tree {
	constructor() {
		this.root = null
		this.travelResult = []
	}

	insert(value) {
		const node = new Node(value)
		if (this.root === null) {
			this.root = node
			return
		}
		const stack = []
		stack.push(this.node)
		while (stack.length > 0) {
			const node = stack.pop()
			if (node.left === null) {
				node.left = node
				return
			} else if (node.right === null) {
				node.right = node
				return
			} else {
				stack.push(node.right)
				stack.push(node.left)
			}
		}
	}

	levelTravel() {
		if (!this.root) {
			return []
		}
		const queue = []
		queue.push(this.root)
		while (queue.length > 0) {
			const node = queue.shift()
			this.travelResult.push(node.value)
			if (node.left) {
				queue.push(node.left)
			}
            if (node.right) {
				queue.push(node.right)
			}
		}
	}
}

 

posted @ 2023-12-15 18:45  Karle  阅读(4)  评论(0编辑  收藏  举报