Advertisement
stanevplamen

Tree traversals

Sep 24th, 2022
706
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.82 KB | Software | 0 0
  1. // javascript program for different tree traversals
  2.  
  3. /* Class containing left and right child of current
  4.    node and key value*/
  5. class Node {
  6.     constructor(val) {
  7.         this.key = val;
  8.         this.left = null;
  9.         this.right = null;
  10.     }
  11. }
  12.  
  13. // Root of Binary Tree
  14. var root = null;
  15.  
  16.    
  17. /*
  18.     * Given a binary tree, print its nodes according to the "bottom-up" postorder
  19.     * traversal.
  20.     */
  21. function printPostorder(node) {
  22.     if (node == null)
  23.         return;
  24.  
  25.     // first recur on left subtree
  26.     printPostorder(node.left);
  27.  
  28.     // then recur on right subtree
  29.     printPostorder(node.right);
  30.  
  31.     // now deal with the node
  32.     document.write(node.key + " ");
  33. }
  34.  
  35. /* Given a binary tree, print its nodes in inorder */
  36. function printInorder(node) {
  37.     if (node == null)
  38.         return;
  39.  
  40.     /* first recur on left child */
  41.     printInorder(node.left);
  42.  
  43.     /* then print the data of node */
  44.     document.write(node.key + " ");
  45.  
  46.     /* now recur on right child */
  47.     printInorder(node.right);
  48. }
  49.  
  50. /* Given a binary tree, print its nodes in preorder */
  51. function printPreorder(node) {
  52.     if (node == null)
  53.         return;
  54.  
  55.     /* first print data of node */
  56.     document.write(node.key + " ");
  57.  
  58.     /* then recur on left subtree */
  59.     printPreorder(node.left);
  60.  
  61.     /* now recur on right subtree */
  62.     printPreorder(node.right);
  63.    
  64. }
  65.  
  66.  
  67.  
  68. // Driver method
  69.    
  70.    
  71. root = new Node(1);
  72. root.left = new Node(2);
  73. root.right = new Node(3);
  74. root.left.left = new Node(4);
  75. root.left.right = new Node(5);
  76.  
  77. document.write("Preorder traversal of binary tree is <br/>");
  78. printPreorder(root);
  79.  
  80. document.write("<br/>Inorder traversal of binary tree is <br/>");
  81. printInorder(root);
  82.  
  83. document.write("<br/>Postorder traversal of binary tree is <br/>");
  84. printPostorder(root);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement