二叉树的非递归遍历

理解好这个问题,对于递归的理解和递归转非递归的方法都有很好的益处。

#include <stdio.h>
#include <stack>
template<typename T>
class TreeNode {
 public:
  TreeNode() : left_(NULL), right_(NULL) {}
  T value_;
  TreeNode* left_;
  TreeNode* right_;
};
template<typename T, typename VisitFun>
void PreOrderVisit(TreeNode<T>* root, VisitFun visit_fun) {
  std::stack<TreeNode<T>*> visit_stack;
  TreeNode<T>* current = root;
  while (current || !visit_stack.empty()) {
    if (current) {
      visit_fun(current);      
      visit_stack.push(current);
      current = current->left_;
      continue;
    }
    current = visit_stack.top();
    visit_stack.pop();
    current = current->right_;
  }
}
template<typename T, typename VisitFun>
void InOrderVisit(TreeNode<T>* root, VisitFun visit_fun) {
  std::stack<TreeNode<T>*> visit_stack;
  TreeNode<T>* current = root;
  while (current ||!visit_stack.empty()) {
    if (current) {
      visit_stack.push(current);
      current = current->left_;
      continue;
    }
    current = visit_stack.top();
    visit_fun(current);
    visit_stack.pop();
    current = current->right_;
  }
}
template<typename T, typename VisitFun>
void PostOrderVisit(TreeNode<T>* root, VisitFun visit_fun) {
  std::stack<TreeNode<T>*> visit_stack;
  TreeNode<T>* current = root;
  TreeNode<T>* previous = NULL;
  while (current || !visit_stack.empty()) {
    if (current) {
      visit_stack.push(current);
      current = current->left_;
      continue;
    }
    current = visit_stack.top();
    if (current->right_ && current->right_ != previous) {
      current = current->right_;
      previous = NULL;
    } else {
      visit_fun(current);
      previous = current;
      visit_stack.pop();
      current = NULL;
    }
  }    
}
void MyVisitFun(TreeNode<int>* current) {
  printf("%d ", current->value_);
}
int main(int argc, char** argv) {
  const int kNodeAmount = 15;
  TreeNode<int> tree[kNodeAmount];
  for (int i = 0; i < kNodeAmount; ++i) {
    tree[i].value_ = i;
  }
  int i = 0;
  int left = 0;
  int right = 0;
  while (true) {
    left = 2 * (i + 1) - 1;
    right = 2 * (i + 1);
    if (left >= kNodeAmount || right >= kNodeAmount) {
      break;
    }
    tree[i].left_ = tree + left;
    tree[i].right_ = tree + right;
    i++;
  }
  PreOrderVisit(tree, MyVisitFun);
  printf("\n");
  InOrderVisit(tree, MyVisitFun);
  printf("\n");
  PostOrderVisit(tree, MyVisitFun);
  printf("\n");
}

参考文献:

http://www.cppblog.com/ngaut/archive/2011/11/27/2351.html

http://bbs.pfan.cn/post-164802.html

http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=331522

你可能感兴趣的:(tree,null,fun)