- 二叉树的遍历
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.push(root);
while(tree.length) {
var node = tree.shift();
result.push(node.val);
if(node.left) {
tree.push(node.left);
}
if(node.right) {
tree.push(node.right);
}
}
return result;
}