- 递归形式的先序、中序、后序 + 非递归层次遍历:
function TreeNode(x){
this.val = x;
this.left = null;
this.right = null;
}
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){
LDR(root.left);
}
console.log(root.val);
if(root.right){
LDR(root.right);
}
}
function LRD(root){
if(root.left){
LRD(root.left);
}
if(root.right){
LRD(root.right);
}
console.log(root.val);
}
function levelTraversal(root){
if(!root) return false;
let result = [];
let tree = [];
tree.push(root);
while(tree.length){
let node = tree.shift();
result.push(node.val);
if(node.left){
tree.push(node.left);
}
if(node.right){
tree.push(node.right);
}
}
return result;
}
let tnode = new TreeNode(3);
tnode.left = {"val":2};
tnode.right = {"val":1};
console.log(tnode);
console.log("先序遍历:");
DLR(tnode);
console.log("中序遍历:");
LDR(tnode);
console.log("后序遍历:");
LRD(tnode);
console.log("层次遍历:",levelTraversal(tnode));

- 非递归形式的先序、中序、后序