中序遍历

也叫中根序遍历,也就是“左根中”

递归

  1. void midOrderTraversal(TreeNode* root) {
  2. if(!root) return;
  3. midOrderTraversal(root->left);
  4. visit(root);
  5. midOrderTraversal(root->right);
  6. }

非递归

  1. void midOrderTraversal(TreeNode* root) {
  2. stack<TreeNode*> stk;
  3. TreeNode* p = root;
  4. while(!stk.empty() || p) {
  5. while(p){
  6. stk.push(p);
  7. p = p->left;
  8. }
  9. if(!stk.empty()){
  10. p = s.top();
  11. s.pop();
  12. visit(p);
  13. p = p->right;
  14. }
  15. }
  16. }

先(前)序遍历

递归

  1. void preOrderTraversal(TreeNode* root) {
  2. if(!root) return;
  3. visit(root);
  4. midOrderTraversal(root->left);
  5. midOrderTraversal(root->right);
  6. }

非递归

  1. void midOrderTraversal(TreeNode* root) {
  2. stack<TreeNode*> stk;
  3. TreeNode* p = root;
  4. while(!stk.empty() || p) {
  5. while(p){
  6. stk.push(p);
  7. visit(p);
  8. p = p->left;
  9. }
  10. if(!stk.empty()){
  11. p = s.top();
  12. s.pop();
  13. p = p->right;
  14. }
  15. }
  16. }

后序遍历

递归

  1. void postOrderTraversal(TreeNode* root) {
  2. if(!root) return;
  3. midOrderTraversal(root->left);
  4. midOrderTraversal(root->right);
  5. visit(root);
  6. }

非递归

  1. void postOrderTraversal(TreeNode* root) {
  2. stack<TreeNode*> stk;
  3. TreeNode* pre = NULL;
  4. while(!stk.empty() || root) {
  5. while(root){
  6. stk.push(root);
  7. root = root->left;
  8. }
  9. root = stk.top();
  10. stk.pop();
  11. if(!root->right || root->right == pre) {
  12. visit(root);
  13. pre = root;
  14. root = NULL;
  15. }
  16. else{
  17. stk.push(root);
  18. root = root->right;
  19. }
  20. }
  21. }