無遞迴中序樹遍歷的 C++ 程式


如果以中序遍歷二叉樹,則首先訪問左子樹,接著訪問根,然後訪問右子樹。中序遍歷按升序輸出鍵。這是無遞迴中序樹遍歷的 C++ 程式。

演算法

Begin  
   Function inOrder():
      Declare a stack s.
      Declare the current node as root.
      While current node is not null and stack is not empty do
         While current node is not null do
            Push the current node on the top of the stack
            Make the left child node as current node
         Point the current node at the top of the stack.
         Pop the top most node from the stack
         Print the current node.
         Make the right node as current node.  
      Insert some elements at root, left node and right node in stack.
      Call the inOrder() function to traverse the tree. 
End.

示例程式碼

 即時演示

#include<bits/stdc++.h>
using namespace std;

struct n {
   int d;
   struct n* l;
   struct n* r;
   n (int d) {
      this->d = d;
      l = r = NULL;
   }
};

void inOrder(struct n *root) {
   stack<n *> s;
   n *current = root;

   while (current != NULL || s.empty() == false) {
      while (current != NULL) {
         s.push(current);
         current = current->l;
      }

      current = s.top();
      s.pop();

      cout << current->d << " ";
      current = current->r;
   }
}

int main() {
   struct n *root = new n(7);

   root->l = new n(6);
   root->r = new n(2);
   root->l->l = new n(1);
   root->l->r = new n(9);

   inOrder(root);
   return 0;
}

輸出

1 6 9 7 2

更新日期:2019 年 7 月 30 日

575 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.