js数据结构☞二叉树遍历
作者:互联网
- 二叉树的遍历
//测试数据:二叉树结构如下:
var root = {
val: 1,
left: {
val: 2,
left: {
val: 4,
},
right: {
val: 5
}
},
right: {
val: 3,
left: {
val: 6,
},
right: {
val: 7
}
}
}
// 前序遍历 (根左右)
function DLR(root) {
console.log(root.val);
if(root.left) DLR(root.left);
if(root.right) DLR(root.right);
}
// 中序遍历 (左根右)
function LDR(root) {
if(root.left) DLR(root.left);
console.log(root.val);
if(root.right) DLR(root.right);
}
// 后序遍历 (左右根)
function LDR(root) {
if(root.left) DLR(root.left);
if(root.right) DLR(root.right);
console.log(root.val);
}
// 层序遍历
function levelTraversal(root) {
if(!root) return false; // 如果头节点为空,返回为假
var result = [], tree = []; // tree是存放二叉树的结果
tree.push(root);
while(tree.length) {
var node = tree.shift(); // 将数组第一个节点放到node中
result.push(node.val); // 读取当前节点的val到result中
if(node.left) {
tree.push(node.left);
}
if(node.right) {
tree.push(node.right);
}
}
return result;
}
标签:node,right,val,js,DLR,遍历,二叉树,root,left 来源: https://blog.csdn.net/zlq_CSDN/article/details/104668224