牛客题霸 [ 实现二叉树先序,中序和后序遍历]C++题解/答案

牛客题霸 [ 实现二叉树先序,中序和后序遍历]C++题解/答案

题目描述

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

题解:

先序,中序,后序都是按照各自规律的
先序的遍历顺序是中前后
中序是前中后
后序是前后中
这个决定了递归的顺序
比如先序:
先存当前节点
然后遍历左子树
最后遍历右子树
中序:
先遍历左子树
保存节点
再遍历右子树

代码:

/**
 * 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<>>
     */        
    void Left(TreeNode* root,vector<int>& vec){
        if (root != nullptr) {
            vec.push_back(root->val);
            Left(root->left, vec);
            Left(root->right, vec);
        }
    }
     
    void Center(TreeNode* root, vector<int>& vec) {
        if (root != nullptr) {
            Center(root->left, vec);
            vec.push_back(root->val);
            Center(root->right, vec);
        }
    }
     
    void Right(TreeNode* root, vector<int>& vec) {
        if (root != nullptr) {
            Right(root->left, vec);
            Right(root->right, vec);
            vec.push_back(root->val);
        }
    }
     

    vector<vector<int> > threeOrders(TreeNode* root) {
        // write code here
        vector<vector<int>> output(3);
        Left(root, output[0]);
        Center(root, output[1]);
        Right(root, output[2]);
        return output;
    }
};
posted @ 2020-11-09 17:30  回归梦想  阅读(237)  评论(0编辑  收藏  举报