zoukankan      html  css  js  c++  java
  • 二叉树前中后、层次遍历

    #include<iostream>
    #include<stack>
    #include<queue>
    using namespace std;
    
    /*
    二叉树遍历算法递归+非递归:
    前序遍历:根->左->右
    中序遍历:左->根->右
    后序遍历:左->右->根
    层次遍历
    */
    struct TreeNode {
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x): val(x),left(NULL),right(NULL) {}
    };
    
    /*递归版本*/
    void prerecusive(TreeNode *root)
    {
        if (!root) return;
        cout << root->val << " ";
        prerecusive(root->left);
        prerecusive(root->right);
    }
    void inrecusive(TreeNode *root)
    {
        if (!root) return;
        inrecusive(root->left);
        cout << root->val << " ";
        inrecusive(root->right);
    }
    void postrecusive(TreeNode *root)
    {
        if (!root) return;
        postrecusive(root->left);
        postrecusive(root->right);
        cout << root->val << " ";
    }
    
    /*循环版本。栈做辅助*/
    void preiteration(TreeNode *root)
    {
        if (!root) return;
        stack<TreeNode *> s;
        s.push(root);
        while (!s.empty())
        {
         TreeNode *curr=s.top(); cout
    << curr->val << " "; s.pop(); if (curr->right) s.push(curr->right); if (curr->left) s.push(curr->left); } } void initeration(TreeNode *root) { if (!root) return; stack<TreeNode *> s; TreeNode *curr = root; while (curr || !s.empty())//s没有值,第一个判断条件是curr不是空 { if (curr) { s.push(curr); curr = curr->left; } else { cout << s.top()->val << " "; curr = s.top()->right; s.pop(); } } } void postiteration(TreeNode *root) { if (!root) return; stack<TreeNode *> s; s.push(root); TreeNode *curr; TreeNode *visited;//记录子节点已经访问过 while (!s.empty()) { curr = s.top(); /* * 出栈条件: * 对于叶子节点:直接弹出 * 对于非叶子节点:如果已经遍历过其左子节点或右子节点,则弹出 */ if ((!curr->left && !curr->right) || (visited && (curr->left==visited || curr->right == visited))) { cout << curr->val << " "; visited = curr; s.pop(); } else { if (curr->right) s.push(curr->right); if (curr->left) s.push(curr->left); } } } void leveltraverse(TreeNode *root) { if (!root) return; queue<TreeNode *> q; TreeNode *curr; q.push(root); while (!q.empty()) { curr = q.front(); cout << curr->val << " "; q.pop(); if (curr->left) q.push(curr->left); if (curr->right) q.push(curr->right); } }
  • 相关阅读:
    128th LeetCode Weekly Contest Capacity To Ship Packages Within D Days
    128th LeetCode Weekly Contest Pairs of Songs With Total Durations Divisible by 60
    128th LeetCode Weekly Contest Complement of Base 10 Integer
    C# WPF Image控件下对于Base64的转化显示
    C# 进程通信SendMessage和有关消息参数
    123th LeetCode Weekly Contest Broken Calculator
    123th LeetCode Weekly Contest Add to Array-Form of Integer
    人机博弈,吃子棋游戏(一)总序
    oracle 定时任务(DBMS_JOB)
    oracle 查看表的相关信息
  • 原文地址:https://www.cnblogs.com/beixiaobei/p/10914253.html
Copyright © 2011-2022 走看看