二叉樹的概念:https://segmentfault.com/a/1190000000740261
java二叉樹算法:http://www.cnblogs.com/-new/p/6730458.html
二叉樹的遍歷
二叉樹的遍歷(traversing binary tree)是指從根結點出發,按照某種次序依次訪問二叉樹中所有結點,使得每個結點被訪問一次且僅被訪問一次。
二叉樹的遍歷有三種方式,如下:
(1)前序遍歷(DLR),首先訪問根結點,然后遍歷左子樹,最后遍歷右子樹。簡記根-左-右。
(2)中序遍歷(LDR),首先遍歷左子樹,然后訪問根結點,最后遍歷右子樹。簡記左-根-右。
(3)后序遍歷(LRD),首先遍歷左子樹,然后遍歷右子樹,最后訪問根結點。簡記左-右-根。
(4)層次遍歷(廣度優先遍歷):一層一層地遍歷
樹的結構
254733939-544b398b1bae2_articlex.jpg
模擬數據
const tree = {
value: 'A',
left: {
value: 'B',
left: {
value: 'D',
left: {
value: null
},
right: {
value: null
}
},
right: {
value: 'E',
left: {
value: null
},
right: {
value: null
}
}
},
right: {
value: 'C',
left: {
value: 'F',
left: {
value: null
},
right: {
value: null
}
},
right: {
value: 'G',
left: {
value: null
},
right: {
value: null
}
}
}
}
// 前序遍歷(遞歸)
function beforEach() {
const list = []
function recursive(tree) {
if (tree.value) {
list.push(tree.value)
recursive(tree.left)
recursive(tree.right)
}
}
recursive(tree)
return list
}
console.log(beforEach()) // ["A", "B", "D", "E", "C", "F", "G"]
// 中序遍歷(遞歸)
function centerEach() {
const list = []
function recursive(tree) {
if (tree.value) {
recursive(tree.left)
list.push(tree.value)
recursive(tree.right)
}
}
recursive(tree)
return list
}
console.log(centerEach()) // ["D", "B", "E", "A", "F", "C", "G"]
// 后序遍歷(遞歸)
function afterEach() {
const list = []
function recursive(tree) {
if (tree.value) {
recursive(tree.left)
recursive(tree.right)
list.push(tree.value)
}
}
recursive(tree)
return list
}
console.log(afterEach()) // ["D", "E", "B", "F", "G", "C", "A"]
層級遍歷
function levelOrderTraversal(tree) {
var list = []
var que = []
que.push(tree)
while (que.length !== 0) {
var node = que.shift()
if (node.value) list.push(node.value) // 如果存在值,插入數組
if (node.left) que.push(node.left) // 如果存在對象,繼續放入循環里面的數組
if (node.right) que.push(node.right) // 如果存在對象,繼續放入循環里面的數組
}
return list
}
console.log(levelOrderTraversal(tree)) //["A", "B", "C", "D", "E", "F", "G"]
// 數組變成一個二叉樹
// 先把數組里面的變成想要的對象
var ary = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
var list = []
for (var i = 0; i < ary.length; i++) {
list.push({
a: ary[i],
left: null,
right: null
})
}
for (var i = 0; i < Math.floor(list.length / 2) - 1; i++) { // i表示的是根節點的索引,從0開始
if (list[2 * i + 1] !== null) {
// 左結點
list[i].left = list[2 * i + 1];
}
if (list[2 * i + 2] !== null) {
// 右結點
list[i].right = list[2 * i + 2];
}
}
// 判斷最后一個根結點:因為最后一個根結點可能沒有右結點,所以單獨拿出來處理
var lastIndex = Math.floor(list.length / 2) - 1;
// 左結點
list[lastIndex].left = list[lastIndex * 2 + 1]
// 右結點,如果數組的長度為奇數才有右結點
if (list.length % 2 === 1) {
list[lastIndex].right = list[lastIndex * 2 + 2];
}