二叉树遍历
结构如下图
前序遍历
顺序:先输出自己,在输出左边,然后输出右边
function Node(value){
this.value = value;
this.left = null;
this.right = null;
}
var a = new Node("A");
var b = new Node("B");
var c = new Node("C");
var d = new Node("D");
var e = new Node("E");
var f = new Node("F");
var g = new Node("G");
a.left = c;
a.right = b;
c.left = f;
c.right = g;
b.left = d;
b.right = e;
function fun(root){
if(root == null){
return
};
console.log(root.value); //先输出自己
fun(root.left) // 输出左边
fun(root.right) // 输出右边
}
fun(a)
//最终输出结果 A、C、F、G、B、D、E
中序遍历
顺序:先输出左边,在输出自己,然后输出右边
function Node(value){
this.value = value;
this.left = null;
this.right = null;
}
var a = new Node("A");
var b = new Node("B");
var c = new Node("C");
var d = new Node("D");
var e = new Node("E");
var f = new Node("F");
var g = new Node("G");
a.left = c;
a.right = b;
c.left = f;
c.right = g;
b.left = d;
b.right = e;
function fun(root){
if(root == null){
return
};
fun(root.left) // 输出左边
console.log(root.value); //输出自己
fun(root.right) // 输出右边
}
fun(a)
//输出 F、C、G、A、D、B、E
后续遍历
顺序:先输出左边,在输出右边,然后输出自己
function Node(value){
this.value = value;
this.left = null;
this.right = null;
}
var a = new Node("A");
var b = new Node("B");
var c = new Node("C");
var d = new Node("D");
var e = new Node("E");
var f = new Node("F");
var g = new Node("G");
a.left = c;
a.right = b;
c.left = f;
c.right = g;
b.left = d;
b.right = e;
function fun(root){
if(root == null){
return
};
fun(root.left) // 输出左边
fun(root.right) // 输出右边
console.log(root.value); //输出自己
}
fun(a)
//输出:F、G、C、D、E、B、A