二叉树的非递归遍历

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

#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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值