其他分享
首页 > 其他分享> > NC45-实现二叉树的先序、中序和后序遍历

NC45-实现二叉树的先序、中序和后序遍历

作者:互联网

题目描述

分别按照二叉树先序,中序和后序打印所有的节点。

示例1

输入

{1,2,3}

返回值

[[1,2,3],[2,1,3],[2,3,1]]

题解:

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
private:
    vector<int> pre,mid,post;
    
public:
    /**
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > threeOrders(TreeNode* root) {
        // write code here
        vector<vector<int>> res;
        if(root == nullptr) return res;
        
        //vector<int> pre,mid,post;
        preOrder(root);
        midOrder(root);
        postOrder(root);
        
        res = {pre,mid,post};
        return res;
    }
    
    void preOrder(TreeNode* rot)
    {
        if(rot == nullptr) return;
        pre.push_back(rot->val);
        preOrder(rot->left);
        preOrder(rot->right);
    }
    
    void midOrder(TreeNode* rot)
    {
        if(rot == nullptr) return;
        midOrder(rot->left);
        mid.push_back(rot->val);
        midOrder(rot->right);
    }
    
    void postOrder(TreeNode* rot)
    {
        if(rot == nullptr) return;
        postOrder(rot->left);
        postOrder(rot->right);
        post.push_back(rot->val);
    }
};

 

标签:pre,TreeNode,NC45,中序,return,vector,二叉树,root,rot
来源: https://blog.csdn.net/weixin_42148873/article/details/113666083