This is the 9th day of my participation in Gwen Challenge
Traversal: To fetch and view each factor in a collection.
Passing a binary tree passes the root node.
Tree structure has three traversal modes, namely, pre-traversal, mid-traversal and post-traversal.
The former sequence traversal
Pre-order traversal is also called pre-root order traversal. Pre-traversal prints the root node first, then the left subtree, and finally the right subtree. As shown, the preceding traversal is: ABDECFG
Code to achieve a binary tree before traversal
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 = b;
a.right = c;
b.left = d;
b.right = e;
c.left = f;
c.right = g;
function f1(root){
if (root == null) return;
console.log(root.value);
f1(root.left);
f1(root.right);
}
f1(a);
Copy the code
In the sequence traversal
Middle order traversal is also called middle root order traversal. Middle-order traversal prints the left subtree first, then the root node, and finally the right subtree. As shown, its middle order traversal is: DBEAFCG
Code to achieve binary tree order traversal
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 = b;
a.right = c;
b.left = d;
b.right = e;
c.left = f;
c.right = g;
function f1(root){
if (root == null) return;
f1(root.left);
console.log(root.value);
f1(root.right);
}
f1(a);
Copy the code
After the sequence traversal
Post-order traversal is also called post-root order traversal. A back-order traversal prints the left subtree, then the right subtree, and finally the root node. As shown, its subsequent traversal is: DEBFGCA
Code to achieve a binary tree after the sequence traversal
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 = b;
a.right = c;
b.left = d;
b.right = e;
c.left = f;
c.right = g;
function f1(root){
if (root == null) return;
f1(root.left);
f1(root.right);
console.log(root.value);
}
f1(a);
Copy the code