Skip to main content
Library homepage
 
Engineering LibreTexts

5.2: Sample implementations for Tree Traversal

  • Page ID
    47901
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    preorder(node)
     visit(node)
     if node.left ≠ null then preorder(node.left)
     if node.right ≠ null then preorder(node.right)
    
    inorder(node)
     if node.left ≠ null then inorder(node.left)
     visit(node)
     if node.right ≠ null then inorder(node.right)
    
    postorder(node)
     if node.left ≠ null then postorder(node.left)
     if node.right ≠ null then postorder(node.right)
     visit(node)
    
    levelorder(root)
     queue<node> q
     q.push(root)
     while not q.empty do
      node = q.pop
      visit(node)
      if node.left ≠ null then q.push(node.left)
      if node.right ≠ null then q.push(node.right)
    

    For an algorithm that is less taxing on the stack, see Threaded Trees.


    5.2: Sample implementations for Tree Traversal is shared under a CC BY-SA license and was authored, remixed, and/or curated by LibreTexts.

    • Was this article helpful?