首页 > 其他分享 >数据结构140-二叉搜索树-后序遍历代码

数据结构140-二叉搜索树-后序遍历代码

时间:2023-02-11 12:04:02浏览次数:43  
标签:node function 遍历 140 BinarySearchTree 二叉 handler key null


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>封装二叉搜索树</title>
</head>
<body>
<script>
function BinarySearchTree() {
function Node(key) {
this.key = null;
this.left = null;
this.right - null;
}
this.root = null;

BinarySearchTree.prototype.insert = function (key) {
var newNode = new Node(key);
//判断节点是否有值
if (this.root == null) {
this.root = newNode;
} else {
this.insertNode(this.root, newNode);
}
};
BinarySearchTree.prototype.insertNode = function (node, newNode) {
if (newNode.key < node.key) {
if (node.left == null) {
node.left = newNode;
} else {
this.insertNode(node.left, newNode);
}
} else {
if (node.right == null) {
node.right = newNode;
} else {
this.insertNode(node.right, newNode);
}
}
};
//先序遍历
BinarySearchTree.prototype.preOrderTraversal = function (handler) {
this.preOrderTraversalNode(this.root, handler);
};

BinarySearchTree.prototype.preOrderTraversalNode = function (
node,
handler
) {
if (node != null) {
//处理经过的节点
handler(node.key);
this.preOrderTraversalNode(node.left, handler);
this.preOrderTraversalNode(node.right, handler);
}
};
//中序遍历
BinarySearchTree.prototype.middleOrderTraversal = function (handler) {
this.middleOrderTraversalNode(this.root, handler);
};
BinarySearchTree.prototype.middleOrderTraversalNode = function (
node,
handler
) {
if (node != null) {
//处理经过的节点
handler(node.key);
this.preOrderTraversalNode(node.left, handler);
handler(node.key)
this.preOrderTraversalNode(node.right, handler);
}
};
//中序遍历
BinarySearchTree.prototype.postOrderTraversal = function (handler) {
this.postOrderTraversalNode(this.root, handler);
};
BinarySearchTree.prototype.postOrderTraversalNode = function (
node,
handler
) {
if (node != null) {
//处理经过的节点
handler(node.key);
this.postOrderTraversalNode(node.left, handler);
this.postOrderTraversalNode(node.right, handler);
handler(node.key)
}
};
}
</script>
</body>
</html>

标签:node,function,遍历,140,BinarySearchTree,二叉,handler,key,null
From: https://blog.51cto.com/u_15460007/6050164

相关文章