树的非递归前序、中序、后序遍历

  

#include <iostream>
#include <string>
#include <stdlib.h>
#include <vector>
#include <stack>
using namespace std;

 struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };

 class Solution {
 public:
     void preOrder(TreeNode *root) 
     {
         stack<TreeNode *>temp;
         TreeNode *current = root;
         while (current || !temp.empty())
         {
             while (current)
             {
                 temp.push(current);
                 printf("%d ", current->val);
                 current = current->left;
             }
             if (!temp.empty())
             {
                 current = temp.top();
                 temp.pop();
                 current = current->right;
             }
         }
         printf("\n");
     }
     void inOrder(TreeNode *root) 
     {
         stack<TreeNode *> temp;
         TreeNode *current = root;
         while (current || !temp.empty())
         {
             while (current)
             {
                 temp.push(current);
                 current = current->left;
             }
             if (!temp.empty())
             {
                 current = temp.top();
                 temp.pop();
                 printf("%d ", current->val);
                 current = current->right;
             }
         }
         printf("\n");
     }
     void postOrder(TreeNode *root) 
     {
         stack<TreeNode *> temp;
         stack<int> tempResult;;
         TreeNode *current = root;
         temp.push(root);
         while (!temp.empty())
         {
             current = temp.top();
             temp.pop();
             tempResult.push(current->val);
             if (current->left)
             {
                 temp.push(current->left);
             }
             if (current->right)
             {
                 temp.push(current->right);
             }
         }
         while (!tempResult.empty())
         {
             printf("%d ", tempResult.top());
             tempResult.pop();
         }
         printf("\n");
     }
 };
int main()
{
    TreeNode *root = new TreeNode(1);
    TreeNode *left = new TreeNode(2);
    TreeNode *right = new TreeNode(3);
    TreeNode *left_left = new TreeNode(4);
    TreeNode *left_right = new TreeNode(5);
    TreeNode *right_left = new TreeNode(6);
    TreeNode *right_right = new TreeNode(7);

    root->left = left;
    root->right = right;
    left->left = left_left;
    left->right = left_right;
    right->left = right_left;
    right->right = right_right;

    Solution so;
    so.preOrder(root);
    so.inOrder(root);
    so.postOrder(root);
    return 0;
}

 

posted @ 2017-06-16 10:37  Forever-Road  阅读(282)  评论(0编辑  收藏  举报