二叉树的前序、中序、后序、层序遍历

二叉树的前序、中序、后序遍历

  • 前序中序和后序遍历指的是根结点的遍历顺序,先根结点就是前序,中间根结点就是中序,最后遍历根结点就是后续
  • 层序遍历是逐层遍历树.

前序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void preOrder(TreeNode* treeNode,vector<int> &res){//递归实现前序遍历
        if(treeNode==nullptr)
            return;
        res.push_back(treeNode->val);//根节点数据进入容器
        preOrder(treeNode->left,res);//遍历左子树
        preOrder(treeNode->right,res);//遍历右子树        
    }
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        preOrder(root,res);
        return res;
    }
};

中序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void inOrder(TreeNode* treeNode,vector<int> &res){//递归实现中序遍历
        if(treeNode==nullptr)
            return;//递归终止条件
        inOrder(treeNode->left,res);//遍历左子树
        res.push_back(treeNode->val);//节点数据进入容器
        inOrder(treeNode->right,res);//遍历右子树
    }
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        inOrder(root,res);
        return res;
    }
};

后序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void nextOrder(TreeNode* treeNode,vector<int> &res){//递归实现后序遍历
        if(treeNode==nullptr)
            return;//设置递归终止条件
        nextOrder(treeNode->left,res);//先遍历左子树
        nextOrder(treeNode->right,res);//再遍历右子树
        res.push_back(treeNode->val);//根结点数据进入容器,最后遍历根结点
    }
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        nextOrder(root,res);
        return res;
    }
};

你可能感兴趣的:(数据结构与算法,二叉树)