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);
    }
};

 

上一篇:企业不可忽视的数据存储和数据安全问题!


下一篇:无人机项目跟踪记录四十五---姿态解算模块详解(2)