Middle – order traversal of binary tree
Sequential traversal: root left and right
- Accessing the root node
- Preemptive traversal of the left subtree of the root node
- Preemptive traversal of the right subtree of the root node
Non-recursive version of the code implementation
const bt = {
val: 50.left: {
val: 10.left: {
val: 5.left: null.right: null,},right: {
val: 15.left: null.right: null,}},right: {
val: 70.left: {
val: 60.left: null.right: null,},right: {
val: 80.left: null.right: null,}}};const preorder = (root) = > {
if(! root) {return; }
const stack = [root];
while (stack.length) {
const n = stack.pop();
console.log(n.val);
if (n.right) stack.push(n.right);
if(n.left) stack.push(n.left); }};// 50 10 5 15 70 60 80
preorder(bt);
Copy the code
Middle order traversal: left root right
- Middle order traversal of the left subtree of the root node
- Accessing the root node
- Middle order traversal is performed on the right subtree of the root node
Non-recursive version of the code implementation
const bt = {
val: 56.left: {
val: 22.left: {
val: 10.left: null.right: null,},right: {
val: 30.left: null.right: null,}},right: {
val: 81.left: {
val: 77.left: null.right: null,},right: {
val: 92.left: null.right: null,}}};const inorder = (root) = > {
if(! root) {return; }
const stack = [];
let p = root;
while (stack.length || p) {
while (p) {
stack.push(p);
p = p.left;
}
const n = stack.pop();
console.log(n.val); p = n.right; }};// 10 22 30 56 77 81 92
inorder(bt);
Copy the code
Post-order traversal: left and right roots
- A post-order traversal of the left subtree of the root node is performed
- A post-order traversal is performed on the right subtree of the root node
- Accessing the root node
Non-recursive version of the code implementation
const bt = {
val: 23.left: {
val: 16.left: {
val: 3.left: null.right: null,},right: {
val: 22.left: null.right: null,}},right: {
val: 45.left: {
val: 37.left: null.right: null,},right: {
val: 99.left: null.right: null,}}};const postorder = (root) = > {
if(! root) {return; }
const outputStack = [];
const stack = [root];
while (stack.length) {
const n = stack.pop();
outputStack.push(n);
if (n.left) stack.push(n.left);
if (n.right) stack.push(n.right);
}
while(outputStack.length){
const n = outputStack.pop();
console.log(n.val); }}; postorder(bt);Copy the code