牛客网 | 高频面试题 | 实现二叉树先序,中序和后序遍历

文章目录

  • 题目
  • 解析
    • 三次获取三种序列
    • 一次获取三种序列

题目

实现二叉树先序,中序和后序遍历_牛客网

题目描述
	分别按照二叉树先序,中序和后序打印所有的节点。
示例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 {
     
public:
    /**
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型vector>
     */
    vector<vector<int> > threeOrders(TreeNode* root) {
     
        // write code here
        vector<vector<int>> res;
        if(root==nullptr)return res;
        vector<int> preorder,inorder,postorder;
        preorder_traversal(preorder,root);
        inorder_traversal(inorder,root);
        postorder_traversal(postorder,root);
        res.push_back(preorder);
        res.push_back(inorder);
        res.push_back(postorder);
        return res;
    }
    void preorder_traversal(vector<int>& v,TreeNode* root){
     
        if(root==nullptr)return;
        v.push_back(root->val);
        preorder_traversal(v, root->left);
        preorder_traversal(v, root->right);
    }
    void inorder_traversal(vector<int>& v,TreeNode* root){
     
        if(root==nullptr)return;
        inorder_traversal(v, root->left);
        v.push_back(root->val);
        inorder_traversal(v, root->right);
    }
    void postorder_traversal(vector<int>& v,TreeNode* root){
     
        if(root==nullptr)return;
        postorder_traversal(v, root->left);
        postorder_traversal(v, root->right);
        v.push_back(root->val);
    }
        
};

一次获取三种序列

class Solution {
     
public:
    void threeOrders(TreeNode* root, vector<vector<int> > &vect){
     
        if(!root)
            return;
        vect[0].push_back(root->val);
        threeOrders(root->left,vect);
        vect[1].push_back(root->val);
        threeOrders(root->right,vect);
        vect[2].push_back(root->val);
    }
    vector<vector<int> > threeOrders(TreeNode* root) {
     
        vector<vector<int> > vect = {
     {
     },{
     },{
     }};
        threeOrders(root,vect);
        return vect;
    }
};

你可能感兴趣的:(刷题,#,牛客,二叉树,dfs,leetcode,面试)