使用JavaScript實作二叉樹的前序遍歷,中序遍歷,后序遍歷
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function Node(value){
this.value =https://www.cnblogs.com/lanshanxiao/p/ value;
this.left = null;
this.right = null;
}
var nodeA = new Node("a");
var nodeB = new Node("b");
var nodeC = new Node("c");
var nodeD = new Node("d");
var nodeE = new Node("e");
var nodeF = new Node("f");
var nodeG = new Node("g");
nodeA.left = nodeB;
nodeA.right = nodeC;
nodeB.left = nodeD;
nodeB.right = nodeE;
nodeC.left = nodeF;
nodeC.right = nodeG;
//前序遍歷:先列印當前節點,再列印左邊子樹的節點,再列印右邊子樹的節點
//中序遍歷:先列印左邊子樹的節點,再列印當前節點,再列印右邊子樹的節點
//后序遍歷:先列印左邊子樹的節點,再列印右邊子樹的節點,再列印當前節點
//-------前序遍歷---begin-----//
function DLR(root){//前序遍歷
if(root == null) return;
console.log(root.value);//先輸出
DLR(root.left);
DLR(root.right);
}
DLR(nodeA);//a b d e c f g
//-------前序遍歷---end-----//
//-------中序遍歷---begin-----//
function LDR(root){//前序遍歷
if(root == null) return;
LDR(root.left);
console.log(root.value);
LDR(root.right);
}
LDR(nodeA);//d b e a f c g
//-------中序遍歷---end-----//
//-------后序遍歷---begin-----//
function LRD(root){//前序遍歷
if(root == null) return;
LRD(root.left);
LRD(root.right);
console.log(root.value);
}
LRD(nodeA);//d e b f g c a
//-------后序遍歷---end-----//
</script>
</body>
</html>
二叉樹遍歷
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/58571.html
標籤:JavaScript
上一篇:向強大的SVG邁進
