Data Structure Binary Tree: Inorder Tree Traversal without Recursion

http://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/

 1 #include <iostream>

 2 #include <vector>

 3 #include <algorithm>

 4 #include <queue>

 5 #include <stack>

 6 using namespace std;

 7 

 8 struct node {

 9     int data;

10     struct node *left, *right;

11     node() : data(0), left(NULL), right(NULL) { }

12     node(int d) : data(d), left(NULL), right(NULL) { }

13 };

14 

15 void print(node *root) {

16     stack<node*> S;

17     if (!root) return;

18     node *cur = root;

19     while (1) {

20         if (cur) {

21             S.push(cur);

22             cur = cur->left;

23         }

24         else if (!S.empty()) {

25             cur = S.top();

26             S.pop();

27             cout << cur->data << " ";

28             cur = cur->right;

29         }

30         else break;

31     }

32 }

33 

34 

35 int main() {

36     struct node* root = new node(1);

37     root->left = new node(2);

38     root->right = new node(3);

39     root->left->left = new node(4);

40     root->left->right = new node(5);

41     print(root);

42     return 0;

43 }

 

你可能感兴趣的:(binary)